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
}
相关推荐
历程里程碑1 小时前
LeetCode热题11:盛水容器双指针妙解
c语言·数据结构·c++·经验分享·算法·leetcode·职场和发展
TimberWill8 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit8 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung8 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
天天向上102412 小时前
go 配置热更新
开发语言·后端·golang
LYFlied12 小时前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)
数据结构·算法·leetcode·动态规划
Asus.Blogs13 小时前
SSE + Resty + Goroutine + Channel 完整学习笔记
笔记·学习·golang
sin_hielo14 小时前
leetcode 3074
数据结构·算法·leetcode
程序员-King.14 小时前
day124—二分查找—最小化数组中的最大值(LeetCode-2439)
算法·leetcode·二分查找
赴前尘15 小时前
golang获取一个系统中没有被占用的端口
开发语言·后端·golang