美文网首页
LeetCode 第 220 题题解

LeetCode 第 220 题题解

作者: 李威威 | 来源:发表于2018-11-14 15:10 被阅读10次
image.png

LeetCode 第 220 题:

class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        // 极端条件判断
        int len = nums.length;
        if (len == 0 || k <= 0 || t < 0) {
            return false;
        }
        TreeSet<Long> treeSet = new TreeSet<>();
        for (int i = 0; i < len; i++) {
            Long floor = treeSet.floor((long) nums[i] + t);
            Long ceiling = treeSet.ceiling((long) nums[i] - t);
            if ((floor != null && floor >= nums[i]) || (ceiling != null && ceiling <= nums[i])) {
                return true;
            }
            // 超过 k 的时候,就要移除之前的元素
            // k = 3
            // 0,1,2,3
            if (i >= k) {
                treeSet.remove((long)nums[i - k]);
            }
            treeSet.add((long) nums[i]);
        }
        return false;
    }
}

相关文章

网友评论

      本文标题:LeetCode 第 220 题题解

      本文链接:https://www.haomeiwen.com/subject/ilrjfqtx.html