题目描述:
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.
这里即要考虑到index的信息,又要考虑到value的信息,因为|j-i|<=k, 且|value_i - value_j |<=t; 所以每次只能比较k个元素,可以用移动窗口。
而value之间的差值如果用暴力强解的方法检测,应该是O(n^2)的复杂度,会超时。 可以使用 TreeSet, TreeSet 和 HashSet类似,但时间复杂度稍高一点儿,是O(logN), 但是好处是存储进TreeSet的数值是按顺序排列的,(如何给元素排序可以自己定义), TreeSet本质上是由二叉树实现的。
我们在这里使用TreeSet的ceiling(n)和floor(n) 方法,分别返回Set中比n大的最小值以及比n小的最大值。
每次只考虑k个元素,当元素为k+1个前,将set中第一个元素删除以后再加入第k+1个元素。
代码实现如下:
import java.util.*;
public class ContainsNearbyAlmostDuplicate {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> s=new TreeSet<Integer>();
int num=0,ceil,floor,j=0;
for(int i=0;i<nums.length;i++){
num=nums[i];
if(s.ceiling(num)!=null&&s.ceiling(num)<=num+t||s.floor(num)!=null&&s.floor(num)+t>=num)
return true;
s.add(num);
if(i-j>=k)
{s.remove(nums[j]);
j++;
}
}
return false;
}
public static void main(String[]args){
int[]nums={2,1};
ContainsNearbyAlmostDuplicate c=new ContainsNearbyAlmostDuplicate();
System.out.println(c.containsNearbyAlmostDuplicate(nums,1,1));
}
}