220. Contains Duplicate III

Posted 鱼与海洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了220. Contains Duplicate III相关的知识,希望对你有一定的参考价值。

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

维护一个windon

treeset:

ceiling(E e)

Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
 
floor(E e)
Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
 
remove(Object o)
Removes the specified element from this set if it is present.
 
public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(nums.length < 2 || t < 0) return false;
        TreeSet<Integer> set = new TreeSet<Integer>();
        for(int i = 0 ; i < nums.length; i++){
            Integer floor = set.floor(nums[i] + t);
            Integer ceil = set.ceiling(nums[i] - t);
            if(floor != null && floor >= nums[i] || ceil != null && ceil <= nums[i])
                return true;
            set.add(nums[i]);
            if(i >= k) set.remove(nums[i-k]);
        }
        return false;
    }
}

 

以上是关于220. Contains Duplicate III的主要内容,如果未能解决你的问题,请参考以下文章

220. Contains Duplicate III

Leetcode 220: Contains Duplicate III

220. Contains Duplicate III

[LeetCode] 220. Contains Duplicate III Java

LeetCode220. Contains Duplicate III

220. Contains Duplicate III(核心:set数组有序/桶排序)