220. 存在重复元素 III(滑窗+TreeSet)

class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        int n = nums.length;
        TreeSet<Integer> set = new TreeSet<>();
        int l = 0, r = 0;
        while(r < n) {
            int num = nums[r++];
            if(!set.isEmpty()) {
                if(r - 1 - l <= k) {
                    if((set.floor(num) != null && Math.abs((long)num-set.floor(num)) <= t) || 
                    (set.ceiling(num) != null && Math.abs((long)num-set.ceiling(num)) <= t)) return true;
                }
                if(r - 1 - l == k) {
                    set.remove(nums[l++]);
                }
            }
            set.add(num);
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/yonezu/p/13504162.html