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

Contains Duplicate III

2015-08-06 15:42 453 查看
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.

思路:给定一个整数数组,判断其中是否存在两个不同的下标i和j满足:|
nums[i] - nums[j] | <= t 并且 | i - j | <= k。利用TreeSet中的ceiling()方法和floor()方法,来确定滑动窗口内的是否差小于等于t

代码如下:

public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if(nums==null || k<1 || t<0) return false;
TreeSet<Integer> set = new TreeSet<>();
for(int i=0;i<nums.length;i++){
int n = nums[i];
if(set.ceiling(n)!=null&&set.ceiling(n)<=t+n || set.floor(n)!=null&& n<=t+set.floor(n)){
return true;
}
set.add(nums[i]);

//保证窗口长度为k
if(i>=k){
set.remove(nums[i-k]);
}
}

return false;

}
}

http://www.tuicool.com/articles/iE3imiQ
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: