Golang | Leetcode Golang题解之第220题存在重复元素III

题目:

题解:

Go 复制代码
func getID(x, w int) int {
    if x >= 0 {
        return x / w
    }
    return (x+1)/w - 1
}

func containsNearbyAlmostDuplicate(nums []int, k, t int) bool {
    mp := 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
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}
相关推荐
ShuiShenHuoLe2 小时前
golang-jwt v5 入门
开发语言·后端·golang
smj2302_796826524 小时前
解决leetcode第4017题数组中的峰值II
python·算法·leetcode
午彦琳4 小时前
2026.9.9
数据结构·算法·leetcode
橘子汽水1685 小时前
Leetcode 200,994岛屿数量,腐烂的橘子
数据结构·算法·leetcode
geovindu6 小时前
go: Task Scheduler
开发语言·后端·golang
Tisfy7 小时前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
find1star8 小时前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
吞下星星的少年·-·8 小时前
LeetCode 热题 100 两数之和(哈希表)
算法·leetcode·哈希算法
FfHUCisI8 小时前
Go 内存分配器概览:从 TCMalloc 到三级缓存架构
缓存·架构·golang
土司大王9 小时前
LeetCode hot100——全排列
java·算法·leetcode