给定一个整数数组,判断是否存在重复元素。
如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
代码:
先将其排序,判断元素是否和下一个元素相等:时间复杂度:NlogN 空间复杂度:logN
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int len = nums.size();
sort(nums.begin(), nums.end());
for(int k=0; k<len-1; k++){
if(nums[k]==nums[k+1]) return true;
}
return false;
}
};
2.将元素插入到哈希表中,插入元素到哈希表中元素在表中,说明存在重复的元素。
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;
//迭代容器中所有的元素,x是元素值,不是地址
for (int x: nums) {
//如果在s里面找到了该元素,说明是重复元素(s.find(x) != s.end()这里s.find(x)返回的是地址,返回的地址不等于s.end()说明找到了该元素)
if (s.find(x) != s.end()) {
return true;
}
s.insert(x);
}
return false;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate
备注:for (auto x : nums)
作用就是迭代容器中所有的元素,每一个元素的临时名字就是x,等同于下边代码
等价于for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)