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
}
相关推荐
smj2302_796826528 小时前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode
leoufung11 小时前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
im_AMBER12 小时前
Leetcode 59 二分搜索
数据结构·笔记·学习·算法·leetcode
leoufung13 小时前
LeetCode 61. 旋转链表(Rotate List)题解与思路详解
leetcode·链表·list
想搞艺术的程序员13 小时前
深入 NSQ 延迟消息实现原理:设计巧思与性能优化
性能优化·golang·nsq
leoufung18 小时前
逆波兰表达式 LeetCode 题解及相关思路笔记
linux·笔记·leetcode
Aspect of twilight20 小时前
LeetCode华为大模型岗刷题
python·leetcode·华为·力扣·算法题
2301_8079973820 小时前
代码随想录-day47
数据结构·c++·算法·leetcode
Elias不吃糖20 小时前
LeetCode每日一练(3)
c++·算法·leetcode
小年糕是糕手1 天前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode