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.
查找nums[i] -nums[j] <=t并且i-j<=k,始终保持一个长度为k的集合,每次判断该集合里是否存在与该元素相差t的元素,考虑到需要排序可直接利用有序集合SortedSet然后截取符合元素的子集合
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if(k<1 || t<0 || nums==null || nums.length<2) return false;
SortedSet<Integer> set = new TreeSet<Integer>();
for(int j=0; j<nums.length; j++) {
SortedSet<Integer> subSet = set.subSet(nums[j]-t, nums[j]+t+1);
if(!subSet.isEmpty()) return true;
if(j>=k) {
set.remove(nums[j-k]);
}
set.add(nums[j]);
}
return false;
}