代码
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t){
if(t<0) return false;
HashMap<Long,Long> map=new HashMap<>();
//
long w=t+1;
for(int i=0;i<nums.length;i++)
{
long bucketId = getBucketId(nums[i], w);
if(map.containsKey(bucketId))
{
return true;
}
if(map.containsKey(bucketId-1)&&Math.abs(nums[i]-map.get(bucketId-1))<=t){
return true;
}
if(map.containsKey(bucketId+1)&&Math.abs(nums[i]-map.get(bucketId+1))<=t){
return true;
}
map.put(bucketId,(long)nums[i]);
if(map.size()>k) map.remove(getBucketId(nums[i-k],w));
}
return false;
}
//举一下例子,就可以判断如何生成桶的编号
public long getBucketId(int num,long t)
{
return num<0?(long)num+1/t-1:(long)num/t;
}