java treeset solution easy and fast


  • 0
    G
    public class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if(k<1 || t<0){
                return false;
            }
            
            TreeSet<Integer> set = new TreeSet<>();
            
            for(int i=0;i<nums.length;i++){
                int temp = nums[i];
                
                //已经遍历过的数有存在和当前数差值绝对值小于等于t的情况,返回true.
                if((set.floor(temp)!=null && temp<=set.floor(temp)+t) ||(set.ceiling(temp)!=null && temp>=set.ceiling(temp)-t)){
                    return true;
                }
                set.add(temp);
                if(i>=k){
                    set.remove(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.