forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontains-duplicate-iii_1_AC.cpp
79 lines (72 loc) · 1.75 KB
/
contains-duplicate-iii_1_AC.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// So many edge cases, what a headache...
// Still, balanced BST is good stuff.
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <map>
using std::abs;
using std::map;
using std::min;
using std::next;
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (k < 0 || t < 0) {
return false;
}
++k;
int n = nums.size();
if (n < 2) {
return false;
}
map<int, int> mm;
bool found = false;
k = min(k, n);
int i = 0;
while (!found && i < k) {
++mm[nums[i]];
if(checkNearby(mm, nums[i], t)) {
found = true;
}
++i;
}
while (!found && i < n) {
--mm[nums[i - k]];
if (mm[nums[i - k]] == 0) {
mm.erase(nums[i - k]);
}
++mm[nums[i]];
if(checkNearby(mm, nums[i], t)) {
found = true;
}
++i;
}
mm.clear();
return found;
}
private:
bool checkNearby(map<int, int> &mm, int num1, int diff) {
auto it = mm.find(num1);
if (it->second > 1) {
return true;
}
int num2;
if (it != mm.begin()) {
--it;
num2 = it->first;
++it;
if (abs((int64_t)num1 - num2) <= diff) {
return true;
}
}
if (next(it) != mm.end()) {
++it;
num2 = it->first;
--it;
if (abs((int64_t)num1 - num2) <= diff) {
return true;
}
}
return false;
}
};