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
每日一道Leetcode - 220. 存在重复元素 III 【桶排序】
最新推荐文章于 2023-09-18 03:56:34 发布