publicbooleancontainsNearbyAlmostDuplicate(int[] nums,int k,int t) {TreeSet<Integer> set =newTreeSet<>();for (int i =0; i <nums.length; ++i) {// Find the successor of current elementInteger s =set.ceiling(nums[i]);if (s !=null&& s <= nums[i] + t) returntrue;// Find the predecessor of current elementInteger g =set.floor(nums[i]);if (g !=null&& nums[i] <= g + t) returntrue;set.add(nums[i]);if (set.size() > k) {set.remove(nums[i - k]); } }returnfalse;}
要注意一个test case:
BST solution is incorrect in following case:
[-1, 2147483647]
1
2147483647
Using Buckets
20 ms, faster than 89.87%
Inspired by bucket sort, we can achieve linear time complexity in our problem using buckets as window.