Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/)(Medium)
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.
题目大意:
给定一个整数数组,判断其中是否存在两个不同的下标i和j满足:| nums[i] - nums[j] | <= t 并且 | i - j | <= k
解题思路: 维护一个大小为 k的二叉搜索树,来一个新的元素时,在BST上二分搜索有没有符合条件的数对,动态更新这个BST。因为BST的大小为 k 或不超过 k,所以这里面的数下标的差值一定是符合条件的。
TreeMap is implemented as a red black tree, which is a self-balancing binary search tree.
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (k < 1 || t < 0)
return false;
TreeSet<Integer> set = new TreeSet<Integer>();
for (int i = 0; i < nums.length; i++) {
int c = nums[i];
if ((set.floor(c) != null && c <= set.floor(c) + t)
|| (set.ceiling(c) != null && c >= set.ceiling(c) -t))
return true;
set.add(c);
if (i >= k)
set.remove(nums[i - k]);
}
return false;
}