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.
Show Similar Problems
Have you met this question in a real interview?
思路: Using binary search tree to storage the element.
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Long> set = new TreeSet<>();
for(int i = 0; i < nums.length; i++) {
if(i > k) set.remove(Long.valueOf(nums[i - k - 1]));
long upperBound = (long)nums[i] + t;
long lowerBound = (long)nums[i] - t;
Long lower = set.lower(upperBound + 1);
if(lower != null && lower >= lowerBound) return true;
set.add(Long.valueOf(nums[i]));
}
return false;
}
}