题目链接
题目描述
给你一个整数数组 nums 和两个整数 k 和 t 。请你判断是否存在 两个不同下标 i 和 j,使得 abs(nums[i] - nums[j]) <= t ,同时又满足 abs(i - j) <= k 。
如果存在则返回 true,不存在返回 false。
示例 1:
输入:nums = [1,2,3,1], k = 3, t = 0
输出:true
示例 2:输入:nums = [1,0,1,1], k = 1, t = 2
输出:true
示例 3:输入:nums = [1,5,9,1,5,9], k = 2, t = 3
输出:false
提示:
0 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
0 <= k <= 104
0 <= t <= 231 - 1
解题思路
桶排序思想:每个桶只装一个元素,总共有t+1个桶,如果桶是存在的,说明满足条件,返回True,如果不存在,看是否存在相邻的桶,并检查其中的元素。
代码
Python
class Solution:
def containsNearbyAlmostDuplicate(self, nums: list[int], k: int, t: int) -> bool:
def getID(x: int, w: int) -> int:
if x >= 0:
return x // w
return (x + 1) // w - 1
mp = {}
for idx, num in enumerate(nums):
id = getID(num, t + 1)
if id in mp:
return True
elif id - 1 in mp and abs(num - mp[id - 1]) <= t:
return True
elif id + 1 in mp and abs(num - mp[id + 1]) <= t:
return True
mp[id] = num
if idx - k >= 0:
del mp[getID(nums[idx - k], t + 1)]
return False
Go
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
func getID(x, w int) int {
if x >= 0 {
return x / w
}
return (x+1)/w - 1
}
func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool {
mp := make(map[int]int)
for i, x := range nums {
id := getID(x, t+1)
if _, has := mp[id]; has {
return true
}
if y, has := mp[id-1]; has && abs(x-y) <= t {
return true
}
if y, has := mp[id+1]; has && abs(x-y) <= t {
return true
}
mp[id] = x
if i >= k {
delete(mp, getID(nums[i-k], t+1))
}
}
return false
}