
LeetCode 第 220 题:
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
// 极端条件判断
int len = nums.length;
if (len == 0 || k <= 0 || t < 0) {
return false;
}
TreeSet<Long> treeSet = new TreeSet<>();
for (int i = 0; i < len; i++) {
Long floor = treeSet.floor((long) nums[i] + t);
Long ceiling = treeSet.ceiling((long) nums[i] - t);
if ((floor != null && floor >= nums[i]) || (ceiling != null && ceiling <= nums[i])) {
return true;
}
// 超过 k 的时候,就要移除之前的元素
// k = 3
// 0,1,2,3
if (i >= k) {
treeSet.remove((long)nums[i - k]);
}
treeSet.add((long) nums[i]);
}
return false;
}
}
网友评论