首页 > 其他 > 详细

leetcode 220. Contains Duplicate III

时间:2019-04-07 23:38:00      阅读:158      评论:0      收藏:0      [点我收藏+]

Compared with contains duplicate II, we should record a sorted set within the length k window.
So when we visit a new value, we can get the floor and ceiling of this value, if value - floor <= t or ceiling - value <= t, then return true.
And before the code we can have a review on some retrieve methods in NavigableSet

E lower(E e) means less than or null
E floor(E e) means less equal or null
E higher(E e) means bigger than or null
E ceiling(E e) means bigger equal or null

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

leetcode 220. Contains Duplicate III

原文:https://www.cnblogs.com/exhausttolive/p/10667990.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!