*LeetCode-Contains Duplicate III

来源:互联网 发布:js移除元素的属性值 编辑:程序博客网 时间:2024/05/17 06:45

本来想像第二道题一样用一个k 大小的set维持一个连续的window 然后每次取这个set最大值最小值 然后和下一个数取diff

但是超时了

需要用tree set 有两个很有用的function floor 和 ceiling 分别

Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.

Returns the least element in this set greater than or equal to the given element, or null if there is no such element.

所以判断条件是 找到这样的floor 并且floor的方向正确 大于num[i]即表示在num [ i ]到 num[ i ] +  k找到了一个数

或者找到了在num [ i ] -k 到 num[ i ] 找到了一个数

注意每次先判断这些 然后没有return的话 add这个num[i]然后假如个数超了 就remove头上一个

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


0 0
原创粉丝点击