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;
}
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;
}
相关文章推荐
- 220. Contains Duplicate III
- leetcode 220. Contains Duplicate III
- LeetCode *** 220. Contains Duplicate III (set::lower_bound)
- [LeetCode]220. Contains Duplicate III
- 220. Contains Duplicate III
- [leetcode]220. Contains Duplicate III
- 220. Contains Duplicate III
- 220. Contains Duplicate III
- 220. Contains Duplicate III
- LeetCode 220. Contains Duplicate III *****理解条件,查找表
- 220. Contains Duplicate III
- 217, 219,220. Contains Duplicate I, II, III
- LeetCode 220. Contains Duplicate III
- 220. Contains Duplicate III
- leetcode 220. Contains Duplicate III
- 220. Contains Duplicate III
- 【LeetCode】220. Contains Duplicate III
- [leetcode] 220. Contains Duplicate III 解题报告
- #leetcode#220. Contains Duplicate III
- [LeetCode]217. Contains Duplicate&219. Contains Duplicate II&220. Contains Duplicate III