题目链接:https://leetcode.com/problems/contains-duplicate-iii/#/description
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.
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
long long t_long=t;
set<long long> window; // set is ordered automatically
for (int i = 0; i < nums.size(); i++) {
if (i > k) window.erase((long long)nums[i-k-1]); // keep the set contains nums i j at most k
// |x - nums[i]| <= t ==> -t <= x - nums[i] <= t;
// x-nums[i] >= -t ==> x >= nums[i]-t
auto pos = window.lower_bound((long long)(nums[i] - t_long));
// x - nums[i] <= t ==> x <= t+nums[i]
if (pos != window.end() && *pos <= (long long)(t_long+nums[i])) return true;
window.insert((long long)nums[i]);
}
return false;
}
};