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
}
相关推荐
吞下星星的少年·-·9 小时前
LeetCode 热题 100 最长连续序列(哈希表)
算法·leetcode·散列表
Pniubi11 小时前
力扣25.K个一组反转链表
算法·leetcode·链表
sunly_12 小时前
Go 切片详解
开发语言·oracle·golang
小白的高手之路12 小时前
【LeetCode 热题 100】560. 和为 K 的子数组|前缀和、哈希表(Python)
数据结构·笔记·python·算法·leetcode·力扣·散列表
利威尔xu15 小时前
Go interface 底层:空接口装任何东西,类型断言漏写 ok 直接 panic 拖垮服务
开发语言·golang·interface·类型断言·itab
Zenova EdgeOS15 小时前
Go Redis 实战:工业边缘场景下的 go-redis
数据库·redis·golang·边缘计算·工业网关
劲夫学编程16 小时前
leetcode: 字母异位词分组
算法·leetcode
wy_hhxx16 小时前
[Leetcode] 动态规划(打家劫舍、0-1背包、完全背包)
算法·leetcode·动态规划·完全背包·0-1背包
Shaoshing17 小时前
LeetCode100 32.最长有效括号
java·数据结构·leetcode
小白的高手之路18 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣