217. Contains Duplicate
# Easy
Three methods:
1) use set, compare size of the set before and after insert a number; set.insert()
2) use unordered_map, search map if contain each number;
m.find(), m.end()
3) first sort, then compare neighbor two numbers if equal.
sort(num.begin(), nums.end()) change the original list
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
// edge case
if(nums.size() <= 1) return false;
// regular case
set<int> s;
for(auto a: nums) {
int n = s.size();
s.insert(a);
if(n == s.size()) return true;
}
return false;
}
};
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
// edge case
if(nums.size() <= 1) return false;
// regular case
unordered_map<int, int> m;
for(auto a : nums) {
if(m.find(a) != m.end()) return true;
m[a] = 1;
}
return false;
}
};
Last updated
Was this helpful?