# AC short JAVA Solution using TreeSet and subSet function

• ``````public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> treeset = new TreeSet<>();
for (int i = 0; i < nums.length; ++i) {
Integer floor = nums[i] - t;
Integer ceiling = nums[i] + t + 1;
if ((long) nums[i] - (long) (t) < -2147483647) floor = Integer.MIN_VALUE;
if ((long) nums[i] + (long) (t) + 1 > 2147483646)  ceiling = Integer.MAX_VALUE;
if (t >= 0 && treeset.subSet(floor, ceiling).size() != 0) return true;
treeset.add(nums[i]);
if (i >= k) treeset.remove(nums[i - k]);
}
return false;
}
}
``````

I used subSet function to easily handle BST search. Also, to deal with overflowing , I used (long). Is there any better improvement?

• You can handle it in this way:

``````int floor = nums[i]<Integer.MIN_VALUE+t ?Integer.MIN_VALUE:nums[i]-t;
int ceiling = nums[i]>Integer.MAX_VALUE-t ?Integer.MAX_VALUE:nums[i]+t;``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.