- 用哈希表保存已遍历元素,遍历时发现元素已存在哈希表中则说明有重复元素,时间复杂度
O(n)
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;
for (auto& x : nums) {
if (s.count(x)) {
return true;
}
s.emplace(x);
}
return false;
}
};