-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path220.contains-duplicate-iii.cpp
More file actions
67 lines (65 loc) · 1.93 KB
/
220.contains-duplicate-iii.cpp
File metadata and controls
67 lines (65 loc) · 1.93 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* @lc app=leetcode id=220 lang=cpp
*
* [220] Contains Duplicate III
*/
// @lc code=start
#include <unordered_map>
class Solution {
public:
int getBucketId(int num) {
if (num >= 0) {
return num / diffPlusOne;
}
else {
return (num + 1) / diffPlusOne - 1;
}
}
#if 1 // Time Limit Exceeded
bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
diffPlusOne = valueDiff + 1;
bucket.clear();
for (int i = 0; i < nums.size(); ++i) {
int bucketId = getBucketId(nums[i]);
auto found = bucket.find(bucketId);
if (found != bucket.end()) {
return true;
}
found = bucket.find(bucketId + 1);
if (found != bucket.end()) {
if (abs(found->second - nums[i]) <= valueDiff) {
return true;
}
}
found = bucket.find(bucketId - 1);
if (found != bucket.end()) {
if (abs(found->second - nums[i]) <= valueDiff) {
return true;
}
}
bucket.insert({bucketId, nums[i]});
if (i - indexDiff >= 0) {
int bucketToRemove = getBucketId(nums[i - indexDiff]);
bucket.erase(bucketToRemove);
}
}
return false;
}
#else // Time Limit Exceeded
bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
for (int i = 0; i < nums.size(); ++i){
for (int j = i + 1; j <= i + indexDiff && j < nums.size(); ++j){
if (abs(nums[i] - nums[j]) <= valueDiff) {
cout << i << ',' << j << endl;
return true;
}
}
}
return false;
}
#endif
private:
long diffPlusOne;
unordered_map<int, int> bucket;
};
// @lc code=end