一、Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

分析:先把数组排个序,然后遍历排序后的数组,查看相邻元素是否有重复,时间复杂度O(nlogn)。

class Solution {
public:
bool containsDuplicate(vector<int>& nums) { if( (nums.size() == 0) || (nums.size() == 1) ) return false; std::sort(std::begin(nums), std::end(nums)); //sort()是c++、java里对数组的元素进行排序的方法,包含于头文件algorithm。 for(int i = 0; i < nums.size()-1; i++)
if(nums[i] == nums[i+1]) return true; return false;
}
}; 

其他解法:(集和多集的区别是:set支持唯一键值,set中的值都是特定的,而且只出现一次;而multiset中可以出现副本键,同一值可以出现多次。)

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
set<int> s(nums.begin(), nums.end());
if (nums.size() == s.size()) return false;
else return true;
}
};

或者:

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
vector <bool> vec;
vec.push_back(false);
if (nums.size()<=1){
return false;
}
for (int i=0; i<nums.size();i++){
int m=nums[i];
if (m>=vec.size()){
for (int j=vec.size();j<=m;j++){
vec.push_back(false);
}
}
if (m<vec.size()){
if (vec[m]==true){
return true;
}
else{
vec[m]=true;
}
}
}
return false;
}
};

 或:sort the vector then traverse to find whether there are same value element continuesly:

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
if (nums.size() == 0){
return false;
}
vector<int>::iterator it = nums.begin();
int temp = *it;
it++;
for (; it != nums.end(); it++){
if (*it == temp){
return true;
}
temp = *it;
} return false;
}
};

或: step 1 Sort the vector
step2 use erase to remove the duplicate and compare the size of the vector

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int pre = nums.size(); sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end()); int post = nums.size(); return (post == pre) ? false : true;
return false;
}
};

或:use hash map

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> hash;
vector<int>::iterator it = nums.begin(); for (; it != nums.end(); it++){
if (hash.find(*it) != hash.end()){
return true;
}
hash[*it] = 1;
} return false;
}
};

二、Contains Duplicate II

Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.(注:at most 最多)

分析:题意为---给一个整型数组及整数k,找出是否存在不同的i和j使得nums[i] = nums[j]且i 和j之差最多为k

代码如下:

The basic idea is to maintain a set s which contain unique values from nums[i - k] to nums[i - 1], if nums[i] is in set s then return true else update the set.

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_set<int> s; if (k <= 0) return false;
if (k >= nums.size()) k = nums.size() - 1; for (int i = 0; i < nums.size(); i++)
{
if (i > k) s.erase(nums[i - k - 1]);
if (s.find(nums[i]) != s.end()) return true;
s.insert(nums[i]);
} return false;
}
};

  或:

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (!k)
return false; // fill set
unordered_set<int> h;
size_t size = k<nums.size()?k:nums.size();
for(int i=0;i<size;++i){
if(h.find(nums[i])!=h.end()) //find(value)返回value所在位置,找不到value将返回end()
return true;
h.insert(nums[i]);
}
// check dublicates
size = nums.size();
for(int i=k;i<size;++i){
if(h.find(nums[i])!=h.end())
return true;
h.erase(nums[i-k]); //erase(value) 移除set容器内元素值为value的所有元素,返回移除的元素个数
h.insert(nums[i]);
}
return false;
}
};

或:

其中:unique()函数是一个去重函数,STL中unique的函数 unique的功能是去除相邻的重复元素(只保留一个),还有一个容易忽视的特性是它并不真正把重复的元素删除。他是c++中的函数,所以头文件要加#include<iostream.h>,具体用法如下:

int num[100];

unique(num,mun+n)返回的是num去重后的尾地址,之所以说比不真正把重复的元素删除,其实是,该函数把重复的元素一到后面去了,然后依然保存到了原数组中,然后返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if(nums.empty()||k<1)
return false;
vector<int> temp=nums;
sort(temp.begin(),temp.end());
auto it=unique(temp.begin(),temp.end());
if(it==temp.end())
return false;
for(auto it1=nums.begin();it1!=nums.end()-1;++it1){
auto it2=find(it1+1,nums.end(),*it1); //从it1+1到nums.end()查找与指向it1的值相同的索引
if(it2!=nums.end()){
if(it2-it1<=k){
return true;
}
}
}
return false;
} };

  

 

  

  

  

 

leetcode:Contains Duplicate和Contains Duplicate II的更多相关文章

  1. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  2. [LeetCode] 95. Unique Binary Search Trees II(给定一个数字n,返回所有二叉搜索树) ☆☆☆

    Unique Binary Search Trees II leetcode java [LeetCode]Unique Binary Search Trees II 异构二叉查找树II Unique ...

  3. 【python】Leetcode每日一题-反转链表 II

    [python]Leetcode每日一题-反转链表 II [题目描述] 给你单链表的头节点 head 和两个整数 left 和 right ,其中 left <= right .请你反转从位置 ...

  4. 【LeetCode】522. Longest Uncommon Subsequence II 解题报告(Python)

    [LeetCode]522. Longest Uncommon Subsequence II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemin ...

  5. 【LeetCode】217 & 219 - Contains Duplicate & Contains Duplicate II

     217 - Contains Duplicate Given an array of integers, find if the array contains any duplicates. You ...

  6. [Leetcode] Remove duplicate from sorted list ii 从已排序的链表中删除重复结点

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb ...

  7. 【leetcode❤python】 219. Contains Duplicate II

    #-*- coding: UTF-8 -*-#遍历所有元素,将元素值当做键.元素下标当做值#存放在一个字典中.遍历的时候,#如果发现重复元素,则比较其下标的差值是否小于k,#如果小于则可直接返回Tru ...

  8. LeetCode(219) Contains Duplicate II

    题目 Given an array of integers and an integer k, find out whether there are two distinct indices i an ...

  9. LeetCode Array Easy 219. Contains Duplicate II

    ---恢复内容开始--- Description Given an array of integers and an integer k, find out whether there are two ...

随机推荐

  1. java中的匿名内部类

    匿名内部类在java编码中不是很常见,它可一让类实现多继承的特性(多个父类~1个子类) java中的匿名内部类总结http://www.cnblogs.com/nerxious/archive/201 ...

  2. hadoop安装问题

    1. 运行start-dfs.sh启动HDFS守护进程,start-yarn.sh面向YARN的资源器和节点管理器,资源管理器web地址是http://localhost:8080/.输入stop.d ...

  3. MVC中 ViewBag、ViewData和TempData区别

    MVC3中 ViewBag.ViewData和TempData的使用和区别 public dynamic ViewBag { get; } public ViewDataDictionary View ...

  4. 《Thinking in C++》学习笔记(一)【第二章】

    第二章 对象的创建与使用 2.1语言的翻译过程 翻译器分为两类:解释器(interpreter)和编译器(compiler). 2.1.1解释器 解释器将源代码转化成一些动作(它可由许多机器指令组成) ...

  5. java 静态构造函数

    在java中貌似是没有静态构造函数的. 不过用下面的方式同样可以实现效果. static { }//end 这是静态代码块

  6. EF框架批量更新

    var customers = db.Customers.Where(c => c.name=='小明'); foreach (var customer in customers) { cust ...

  7. Spring mvc json null

    http://blog.csdn.net/zdsdiablo/article/details/9429263

  8. CI中的控制器中要用model中的方法,是统一写在构造器方法中,还是在每一个方法中分别写

    Q: CI中的控制器中要用model中的方法,是统一写在构造器方法中,还是在每一个方法中分别写 A: 建议统一写,CI框架会自动识别已经加载过的类,所以不用担心重复加载的问题 class C_User ...

  9. POJ 1279 Art Gallery(半平面交求多边形核的面积)

    题目链接 题意 : 求一个多边形的核的面积. 思路 : 半平面交求多边形的核,然后在求面积即可. #include <stdio.h> #include <string.h> ...

  10. CoreData的简单使用(一)数据库的创建

    iOS有多种数据持久化得方式 plist文件(属性列表) preference(偏好设置,NSUserDefaults) NSKeyedArchiver(归档,用的不多) SQLite 3 (需要导入 ...