Problem description
:
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.
Analysis:
This problem is sort of harder than previous two problems.
A Easy way is to use sliding window
algorithm.
Maintaining a window size of K, for a new num, if there exists a num in the window also the difference between them is less than t, then return true. (we use lower_bound
to help implementation). When the size is K, we need to erase the old elements.
We use Set to implement the window(avoid using + to prevent overflow)
Here is the code:
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int n = nums.size();
set<int> s;// ordered automatically
for (int i = 0; i < n; ++i)
{
auto lower = s.lower_bound(nums[i] - t); //when s is empty return s.end();
if (lower != s.end() && abs(*lower - nums[i]) <= t)
return true;
s.insert(nums[i]);
if (i >= k) s.erase(nums[i - k]);
}
return false;
}
};