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
}
相关推荐
好易学·数据结构8 小时前
可视化图解算法56:岛屿数量
数据结构·算法·leetcode·力扣·回溯·牛客网
墨染点香10 小时前
LeetCode Hot100【5. 最长回文子串】
算法·leetcode·职场和发展
ん贤11 小时前
如何加快golang编译速度
后端·golang·go
riverz122712 小时前
Go 程序无法使用 /etc/resolv.conf 的 DNS 配置排查记录
golang
im_AMBER13 小时前
Leetcode 03 java
算法·leetcode·职场和发展
轮到我狗叫了13 小时前
力扣.1312让字符串成为回文串的最少插入次数力扣.105从前序和中序遍历构造二叉树牛客.拼三角力扣.57插入区间编辑
算法·leetcode·职场和发展
As_wind_16 小时前
Go 语言学习之测试
开发语言·学习·golang
科大饭桶17 小时前
数据结构自学Day8: 堆的排序以及TopK问题
数据结构·c++·算法·leetcode·二叉树·c
木子.李34717 小时前
记录Leetcode中的报错问题
算法·leetcode·职场和发展
达文汐17 小时前
【中等】题解力扣22:括号生成
java·算法·leetcode·深度优先