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

220. Contains Duplicate III

2017-10-30 20:54 295 查看
原题:

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.

即判断数组里是否有两个元素满足下标距离不超过k,值的差的绝对值不超过t。

解题思路:

这里用一个叫TreeSet的数据结构。维持一个长度为k的窗口,来限制数组下标距离不超过k的条件。添加新元素时判断treeSet里是否有值与当前元素差值不大于t。主要在于treeSet有subSet的函数,可以返回值在一定区域的元素。此方法时间复杂度O(klogn)。

结果代码:

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if ((k == 0 && t > 0) || (k < 0) ||(t < 0)) return false;
TreeSet<Long> treeSet = new TreeSet<>();
for (int i = 0;i < nums.length;i++){
long n = nums[i];
Set<Long> ret = treeSet.subSet(n - (long) t,n + (long) t + 1);
if (!ret.isEmpty()) return true;
if (i >= k) treeSet.remove((long)nums[i - k]);
treeSet.add(n);
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: