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
.
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeMap<Integer,Integer> map=new TreeMap<>();
HashMap<Integer,Integer> helpmap=new HashMap<>();
if(t<0)return false;
for(int i=0;i<=k&&i<nums.length;i++){
if(map.containsKey(nums[i])){
return true;
}
map.put(nums[i],i);
if(map.lowerKey(nums[i])!=null&&nums[i]-map.lowerKey(nums[i])<=t||map.higherKey(nums[i])!=null&&map.higherKey(nums[i])-nums[i]<=t){
if(map.lowerKey(nums[i])!=null){
if(nums[i]-map.lowerKey(nums[i])<0)continue;
}else if(map.higherKey(nums[i])!=null){
if(map.higherKey(nums[i])-nums[i]<0)continue;
}
return true;
}
helpmap.put(i,nums[i]);
}
for(int i=k+1;i<nums.length;i++){
int temp=helpmap.get(i-k-1);
map.remove(temp);
if(map.containsKey(nums[i])){
return true;
}
map.put(nums[i],i);
if(map.lowerKey(nums[i])!=null&&nums[i]-map.lowerKey(nums[i])<=t||map.higherKey(nums[i])!=null&&map.higherKey(nums[i])-nums[i]<=t){
return true;
}
helpmap.put(i,nums[i]);
}
return false;
}
}