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 boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (nums == null || nums.length == 0 || k < 0 || t < 0) {
returnfalse;
}
TreeSet<Long> set = new TreeSet<>();
int left = 0;
int right = 0;
while (right < nums.length) {
if (right - left > k) { //nums[right]的入窗导致窗口大小超过 k 个//左侧出窗set.remove((long)nums[left]);
left++;
}
//待入窗元素nums[right],检查原窗口中是否存在[nums[right] - t, nums[right] + t]范围内的数
Long ceilValue = set.ceiling(((long)nums[right] - t));
if (ceilValue != null && ceilValue <= (long)nums[right] + t) {
//若有,返回truereturntrue;
}
//当前元素入窗set.add((long)nums[right]);
//继续扩窗
right++;
}
returnfalse;
}
}