Java Solution with TreeSet


  • 0
    Y

    You need to check if there is an element x in treeset so that
    -t <= x-nums[i] <= t. Also need to maintain the size k for treeset.

    class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            
            TreeSet<Long> ts = new TreeSet<>();
            for (int i=0; i<nums.length; i++) {
                // -t <= x-nums[i] <= t
                if (ts.floor((long)nums[i]+(long)t) != null 
                    && ts.floor((long)nums[i]+(long)t) >= (long)nums[i]-(long)t) {
                    return true;
                }
                ts.add((long)nums[i]);
                if (i >= k) {
                    ts.remove((long)nums[i-k]);
                }
            }
            return false;
            
        }
    }
    

Log in to reply
 

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