pg

  1. Contains Duplicate III - sliding window

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true


The most important point of this question is that the absolute difference between i and j is at most k.

=> the difference between i and j is in [0, k].

=> we need to check whether there is a number A in the window with size k+1 and the difference between the current number nums[i] and A is <= t.

=> the window is behind current number nums[i] and its size is k+1, because the rightmost number in window is nums[m] and the leftmost number in window is nums[n] and m , n should satisfy m-n = k.

1
2
3
4
5
6
7
8
9
10
11
12
bool (vector<int>& nums, int k, int t)    {
set<long long> window;
for(int i = 0; i < nums.size(); i++){
if(i > k)
window.erase(nums[i-k-1]);
auto it = window.lower_bound((long long)nums[i] - t);
if(it != window.cend() && *it - nums[i] <= t)
return true;
window.insert(nums[i]);
}
return false;
}