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
}
相关推荐
加农炮手Jinx4 小时前
LeetCode 72. Edit Distance 题解
算法·leetcode·力扣
_深海凉_4 小时前
LeetCode热题100-打家劫舍
算法·leetcode·职场和发展
geovindu6 小时前
go: Chain of Responsibility Pattern
开发语言·设计模式·golang·责任链模式
菜鸟丁小真11 小时前
LeetCode hot100 -73.矩阵置零
数据结构·leetcode·矩阵·知识点总结
We་ct12 小时前
LeetCode 64. 最小路径和:动态规划入门实战
开发语言·前端·算法·leetcode·typescript·动态规划
踩坑记录13 小时前
leetcode hot100 169. 多数元素 easy 技巧 摩尔投票
leetcode
水蓝烟雨13 小时前
3487. 删除后的最大子数组元素和
算法·leetcode·链表
菜鸟丁小真14 小时前
LeetCode hot100 -54.螺旋矩阵
算法·leetcode·矩阵·知识点总结
wsoz15 小时前
Leetcode链表-day9
c++·算法·leetcode·链表
6Hzlia16 小时前
【Hot 100 刷题计划】 LeetCode 21. 合并两个有序链表 | C++ 经典迭代与 Dummy 技巧
c++·leetcode·链表