首页 > 其他 > 详细

leetcode-220-存在重复元素③*

时间:2019-10-04 13:56:41      阅读:88      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 方法一:二叉搜索树+滑动窗口

方法二:桶排序 O(N)

class Solution:
    def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
        from collections import OrderedDict
        n = len(nums)
        if n <= 1 or k < 1 or t < 0: return False
        queue = OrderedDict()
        for n in nums:
            key = n if not t else n // t
            for m in [queue.get(key-1), queue.get(key), queue.get(key+1)]:
                if m is not None and abs(n - m) <= t:
                    return True
            if len(queue) == k:
                queue.popitem(False)
            queue[key] = n
        return False

另:

def containsNearbyAlmostDuplicate(self, nums, k, t):
    if t < 0: return False
    n = len(nums)
    d = {}
    w = t + 1
    for i in range(n):
        m = nums[i] // w
        if m in d:
            return True
        if m - 1 in d and abs(nums[i] - d[m - 1]) < w:
            return True
        if m + 1 in d and abs(nums[i] - d[m + 1]) < w:
            return True
        d[m] = nums[i]
        if i >= k: del d[nums[i - k] // w]
    return False

 

leetcode-220-存在重复元素③*

原文:https://www.cnblogs.com/oldby/p/11621989.html

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