-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
ContainsDuplicate.III.cpp
40 lines (34 loc) · 1.35 KB
/
ContainsDuplicate.III.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
// Source : https://leetcode.com/problems/contains-duplicate-iii/
// Author : Hao Chen
// Date : 2015-06-12
/**********************************************************************************
*
* Given an array of integers, find out whether there are two distinct indices i and j
* in the array such that the difference between nums[i] and nums[j] is at most t and
* the difference between i and j is at most k.
*
**********************************************************************************/
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(nums.size() < 2 || k == 0) return false;
int low = 0;
//maintain a sliding window
set<long long> window;
for (int i=0; i<nums.size(); i++){
//make sure window size <= k
if (i - low > k) {
window.erase(nums[low]);
low++;
}
// lower_bound() is the key,
// it returns an iterator pointing to the first element >= val
auto it = window.lower_bound((long long)nums[i] - (long long)t );
if (it != window.end() && abs((long long)nums[i] - *it) <= (long long)t) {
return true;
}
window.insert(nums[i]);
}
return false;
}
};