[LeetCode] Contains Duplicate

217. Contains Duplicate

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;
for(auto& n : nums) {
if(s.count(n)) return true;
s.insert(n);
}
return false;
}
};
  • Time : O(nlogn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
for(int i = 1; i < nums.size(); i++) {
if(nums[i] == nums[i-1])return true;
}
return false;
}
};
  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
return nums.size() != unordered_set<int>(nums.begin(), nums.end()).size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/07/PS/LeetCode/contains-duplicate/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.