Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolutedifference 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
My Solutions:
方法1:brute force
for(int i = 0; i < nums.length-1; i++) {
for(int j = i + 1; j < nums.length && j <= i + k; j++) {
if(Math.abs((long)(nums[i])-nums[j]) <= t) return true;
}
}
return false;
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (k < 1 || t < 0) return false;
TreeSet<Integer> set = new TreeSet<>();
for (int i = 0; i < nums.length; i++) {
int x = nums[i];
if ((set.floor(x) != null && x <= set.floor(x) + t)
|| (set.ceiling(x) != null && x >= set.ceiling(x) - t)) {
return true;
}
set.add(x); //将此element加入bst
if (i >= k) set.remove(nums[i - k]); //把最先加入set的数删去
}
return false;
}
}