LeetCode Contains Duplicate

Contains Duplicate

原题传送门: https://leetcode.com/problems/contains-duplicate/

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

Contains Duplicate II

原题传送门: https://leetcode.com/problems/contains-duplicate-ii/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int len = nums.size();
unordered_set<int> s;
for (int i = 0; i < len; i++) {
if (s.find(nums[i]) == s.end()) {
s.insert(nums[i]);
} else {
return true;
}
if (i >= k) s.erase(nums[i-k]);
}
return false;
}
};

Contains Duplicate III

https://leetcode.com/problems/contains-duplicate-iii/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int len = nums.size();
set<int> s;
set<int>::iterator it;
for (int i = 0; i < len; i++) {
it = s.lower_bound(nums[i]-t);
if (it != s.end() && abs(*it - nums[i]) <= t) {
return true;
} else {
s.insert(nums[i]);
}
if (i >= k) s.erase(nums[i-k]);
}
return false;
}
};