217 存在重复元素

本文最后更新于:2021年1月20日 下午

给定一个整数数组,判断是否存在重复元素。

如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false

示例 1:

1
2
输入: [1,2,3,1]
输出: true

示例 2:

1
2
输入: [1,2,3,4]
输出: false

示例 3:

1
2
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// @lc code=start
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
if(nums.size()<2) return false;
unordered_set<int> record;
for(int i=0; i<nums.size(); ++i){
if(record.find(nums[i]) != record.end())
return true;
record.insert(nums[i]);
}
return false;
}
};
// @lc code=end

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!