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數(shù)據(jù)結(jié)構(gòu)笛厦。
TreeSet數(shù)據(jù)結(jié)構(gòu)(Java)使用紅黑樹(shù)實(shí)現(xiàn)立叛,是平衡二叉樹(shù)的一種悔捶。
該數(shù)據(jù)結(jié)構(gòu)支持如下操作:
floor()方法返set中≤給定元素的最大元素跪者;如果不存在這樣的元素蛀序,則返回 null笙以。
ceiling()方法返回set中≥給定元素的最小元素拴事;如果不存在這樣的元素践剂,則返回 null溉知。
有個(gè)容易bug的地方
n <= t+set.floor(n)
不能寫(xiě)成n - t <= set.floor(n)