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
}
相关推荐
过期动态12 小时前
【LeetCode 热题 100】移动零
java·数据结构·算法·leetcode·职场和发展·rabbitmq
菜菜的顾清寒14 小时前
力扣HOT100(32)二叉树的中序遍历
数据结构·算法·leetcode
csdn_aspnet15 小时前
java 算法 LeetCode 编号 70 - 爬楼梯
java·开发语言·算法·leetcode
_日拱一卒16 小时前
LeetCode:200岛屿数量
算法·leetcode·职场和发展
圣保罗的大教堂17 小时前
leetcode 153. 寻找旋转排序数组中的最小值 中等
leetcode
csdn_aspnet17 小时前
C语言 算法 LeetCode 编号 70 - 爬楼梯
c语言·开发语言·算法·leetcode
菜菜的顾清寒17 小时前
力扣HOT100(31)K 个一组翻转链表
算法·leetcode·链表
x_xbx17 小时前
LeetCode:101. 对称二叉树
算法·leetcode·职场和发展
风筝在晴天搁浅19 小时前
阿里 LeetCode 1189.“气球“的最大数量
算法·leetcode
木井巳19 小时前
【DFS解决floodfill算法】图像渲染
java·算法·leetcode·深度优先