每日一道Leetcode - 220. 存在重复元素 III 【桶排序】

在这里插入图片描述

class Solution:
    def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
        # 使用桶排序
        # 比如说,在一个班上,日期相差30天以内的
        # 一个桶内的元素都是在t的范围内的
        def getIdx(num):
            # 获得当前数据的桶id
            if num < 0:
                return (num + 1) // size - 1
            else:
                return num // size
        bucket = {}
        size = t + 1
        for i,u in enumerate(nums):
            idx = getIdx(u)
            # 如果当前桶已经存在
            if idx in bucket:
                return True
            # 检查相邻桶中的元素是否小于等于t
            # 每个桶中其实只会存一个元素,超出来其实是会返回 
            l,r = idx - 1, idx + 1
            if l in bucket and abs(u-bucket[l])<=t:
                return True
            if r in bucket and abs(u-bucket[r])<=t:
                return True
            # 其他情况,需要建立桶
            bucket[idx] = u
            # 维护k
            if i>=k:
                bucket.pop(getIdx(nums[i-k]))
        return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值