题目描述:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
中文描述:
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
Constraints:
0 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
0 <= k <= 104
0 <= t <= 231 - 1
Time complexity: O(nlogk)
滑动窗口+Binary Search Tree:
- 维持一个区间为k的滑动窗口,这样可以保证滑动窗口内的元素的差的绝对值小于等于k
- 在滑动窗口中寻找与nums[i]最接近的数,即找滑动窗口中小于等于nums[i]的最大值,找滑动窗口中大于等于nums[i]的最小值,若他们任何一个与nums[i]的差的绝对值小于等于t,则直接返回true。注意int 的范围,以及要用TreeSet来维护滑动窗口,因为floor(E x)可以找到小于等于e的最大值,ceiling(E x)可以找到大于等于e的最小值,并且TreeSet本身是排序好的
3、枚举完i位置后,需要将nums[i - k]位置的元素移除滑动窗口,将num[i]位置的元素加入到窗口
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Long> set = new TreeSet<>();
for(int i = 0; i < nums.length; i++){
Long n = (long)nums[i];
Long l = set.floor(n);
Long r = set.ceiling(n);
if (l != null && n - l <= t) return true;
if (r != null && r - n <= t) return true;
set.add(n);
if (set.size() > k) {
set.remove((long)nums[i - k]);
}
}
return false;
}
}