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
}
相关推荐
Charlie_lll3 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
滴滴答滴答答4 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
圣保罗的大教堂4 小时前
leetcode 1980. 找出不同的二进制字符串 中等
leetcode
呆萌很4 小时前
【GO】逻辑运算练习题
golang
礼拜天没时间.5 小时前
力扣热题100实战 | 第25期:K个一组翻转链表——从两两交换到K路翻转的进阶之路
java·算法·leetcode·链表·递归·链表反转·k个一组翻转链表
Swift社区5 小时前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展
再难也得平5 小时前
力扣239. 滑动窗口最大值(Java解法)
算法·leetcode·职场和发展
摩尔曼斯克的海5 小时前
力扣面试题--双指针类
python·算法·leetcode
灰色小旋风5 小时前
力扣——第7题(C++)
c++·算法·leetcode
努力学算法的蒟蒻6 小时前
day106(3.7)——leetcode面试经典150
算法·leetcode·面试