217.Contains Duplicate
Difficulty: Easy
Given an array of integers, find if thearray contains any duplicates. Your function should return true if any valueappears at least twice in the array, and it should return false if everyelement is distinct.
思路
首先是想用到C++的find函数,关联容器自身就提供find操作,关联容器中使用unordered_set比较合适.
顺序遍历nums中元素,调用find判断set容器中是否存在该元素,不存在则给set添加该元素,存在则直接返回true。
代码
[C++]
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> myset;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
if (myset.find(*it) != myset.end())
return true;
myset.insert(*it);
}
return false;
}
};
本文介绍了一种简单有效的算法,用于检查整数数组中是否存在重复元素。通过使用C++中的unordered_set容器,实现了高效的查找功能。文章详细解释了算法的实现过程,并提供了完整的代码示例。
2536

被折叠的 条评论
为什么被折叠?



