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
}
相关推荐
Pniubi10 小时前
力扣76.最小覆盖子串
算法·leetcode·职场和发展
文丑颜不良啊16 小时前
LeetCode2541~2560题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2481~2500题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2521~2540题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2501~2520题目解析
java·leetcode
Pniubi2 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
利威尔xu3 天前
Go map 底层崩溃:3 个 goroutine 并发写同一张 map,fatal error 崩掉整个服务
golang·源码·map·并发·后端开发
Rain的Java大神之路3 天前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode