-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0219-contains-duplicate-ii.cpp
50 lines (40 loc) · 1.15 KB
/
0219-contains-duplicate-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
1 -> 1, 4
- 1
- Keep
- Requires extra memory O(n)
- 2
- Memory O(k) least recently used withj cap k
- 3
- Compute O(nk)
- 4
- unodered_map ->
*/
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> li;
for (int i = 0; i < nums.size(); i++) {
auto num = nums[i];
if (li.count(num)) {
auto prevIndex = li[num];
if ((i - prevIndex) <= k) return true;
}
li[num] = i;
}
return false;
}
};
// class Solution {
// public:
// bool containsNearbyDuplicate(vector<int>& nums, int k) {
// vector<pair<int,int>> indexedNums;
// for(int i = 0; i < nums.size(); i++) indexedNums.push_back(make_pair(nums[i], i));
// sort(indexedNums.begin(), indexedNums.end());
// for(int i = 0; i < nums.size()-1; i++)
// if (indexedNums[i].first == indexedNums[i + 1].first)
// if (abs(indexedNums[i].second - indexedNums[i + 1].second) <= k)
// return true;
// return false;
// }
// };