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

Leetcode_220 Contains Duplicate III

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

查找nums[i] -nums[j] <=t并且i-j<=k,始终保持一个长度为k的集合,每次判断该集合里是否存在与该元素相差t的元素,考虑到需要排序可直接利用有序集合SortedSet然后截取符合元素的子集合

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if(k<1 || t<0 || nums==null || nums.length<2) return false;

SortedSet<Integer> set = new TreeSet<Integer>();

for(int j=0; j<nums.length; j++) {
SortedSet<Integer> subSet =  set.subSet(nums[j]-t, nums[j]+t+1);
if(!subSet.isEmpty()) return true;

if(j>=k) {
set.remove(nums[j-k]);
}
set.add(nums[j]);
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: