Question
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.
Code
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (k < 1 || t < 0 || nums == null || nums.length <= 1) return false;
TreeSet<Integer> set = new TreeSet<>();
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
if ((set.floor(n) != null && n <= t + set.floor(n)) || (set.ceiling(n) != null && set.ceiling(n) <= t + n)) return true;
set.add(n);
if (i >= k) set.remove(nums[i - k]);
}
return false;
}
}
Solution
使用TreeSet數據結構。
TreeSet數據結構(Java)使用紅黑樹實現,是平衡二叉樹的一種。
該數據結構支持如下操作:
floor()方法返set中≤給定元素的最大元素;如果不存在這樣的元素,則返回 null。
ceiling()方法返回set中≥給定元素的最小元素;如果不存在這樣的元素,則返回 null。
有個容易bug的地方
n <= t+set.floor(n)
不能寫成n - t <= set.floor(n)