title
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
Constraints:
0 <= nums.length <= 2 * 104-231 <= nums[i] <= 231 - 10 <= k <= 1040 <= t <= 231 - 1
给定一个整数数组,找出数组中是否有两个不同的索引i和j,使得nums [i]和nums [j]之间差的绝对值最多为t,同时i和j之间差的绝对值最多为k。
solution
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
bucket = {}
for i in range(len(nums)):
index = nums[i] // t if t > 0 else nums[i]
if index in bucket:
return True
bucket[index] = nums[i]
if index - 1 in bucket and abs(bucket[index - 1] - nums[i]) <= t:
return True
if index + 1 in bucket and abs(bucket[index + 1] - nums[i]) <= t:
return True
if i >= k:
del bucket[nums[i - k] // t if t > 0 else nums[i - k]]
return False