您的位置:首页 > 大数据 > 人工智能

leetcode 220. Contains Duplicate III

2017-04-18 23:03 369 查看
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] andnums[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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: