可以用TreeSet来解决问题,但是为了防止溢出的问题,必须将类型强制转化成long(对应的包装类为Long)。
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
// Corner case
if(nums == null || nums.length == 0){
return false;
}
TreeSet<Long> set = new TreeSet<>();
// Sliding window
for(int i = 0; i < nums.length; i++){
// Remove the element of which the distance is larger than k
if(i > k){
set.remove((long) nums[i - k - 1]);
}
// Get the least element which is larger than or equal to the given number
Long ceiling = set.ceiling((long) nums[i] - t);
// Be cautious of the condition in which the return value is null
if(ceiling != null && ceiling <= (long) nums[i] + t){
return true;
}
// Add the curren element into the set
set.add((long) nums[i]);
}
return false;
}
}