桶排序

220. 存在重复元素 III

image.png

  1. class Solution:
  2. def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
  3. bucket = dict()
  4. if t < 0: return False
  5. for i in range(len(nums)):
  6. nth = nums[i] // (t + 1)
  7. if nth in bucket:
  8. return True
  9. if nth - 1 in bucket and abs(nums[i] - bucket[nth - 1]) <= t:
  10. return True
  11. if nth + 1 in bucket and abs(nums[i] - bucket[nth + 1]) <= t:
  12. return True
  13. bucket[nth] = nums[i]
  14. if i >= k: bucket.pop(nums[i - k] // (t + 1))
  15. return False
  1. class Solution(object):
  2. def containsNearbyAlmostDuplicate(self, nums, k, t):
  3. from sortedcontainers import SortedSet
  4. st = SortedSet()
  5. left, right = 0, 0
  6. res = 0
  7. while right < len(nums):
  8. if right - left > k: # 移动窗口
  9. st.remove(nums[left])
  10. left += 1
  11. # 在st中查找nums[right] - t,存在时返回nums[right] - t左侧的位置,不存在返回应该插入的位置.
  12. index = bisect.bisect_left(st, nums[right] - t)
  13. print(st)
  14. if st and index >= 0 and index < len(st) and abs(st[index] - nums[right]) <= t:
  15. return True
  16. st.add(nums[right])
  17. right += 1
  18. return False