Java - TreeSet


  • 0
    public class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            int n = nums.length; 
            if (n <= 1 || t < 0) return false;  
            
            TreeSet<Integer> set = new TreeSet<>();
            for (int i = 0; i < n; i++) {
                if (i > k) set.remove(nums[i - k - 1]);  
                // return if a dup value found
                if (!set.add(nums[i])) return true; 
                // find the greatest element that is less than nums[i]
                if (set.lower(nums[i]) != null && (long)nums[i] - set.lower(nums[i]) <= t) 
                    return true; 
                // find the least element that is greater than nums[i]
                if (set.higher(nums[i]) != null && set.higher(nums[i]) - (long)nums[i] <= t) 
                    return true; 
            }
            return false; 
        }
    }

Log in to reply
 

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