欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Contains Duplicate III

程序员文章站 2022-05-14 13:08:18
...
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。我们用TreeSet来解决,我们维护一个大小为k的treeset,然后通过subSet方法来判断在区间中是否存在和当前元素差小于等于t的元素。为了防止越界,我们将TreeSet设定成长整型。代码如下:

public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if(nums == null || nums.length == 0 || t < 0) return false;
TreeSet<Long> set = new TreeSet<Long>();
set.add((long)nums[0]);
for(int i = 1; i < nums.length; i++) {
if(i > k) set.remove((long)nums[i - k - 1]);
long left = (long)nums[i] - t;
long right = (long)nums[i] + t;
if(!set.subSet(left, right + 1).isEmpty()) return true;
set.add((long)nums[i]);
}
return false;
}
}
相关标签: TreeSet