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
}
相关推荐
小雅痞28 分钟前
[Java][Leetcode simple] 1. 两数之和
java·算法·leetcode
lolo大魔王1 小时前
Go语言的函数与指针的定义
开发语言·后端·golang
codeejun1 小时前
每日一Go-51、Go微服务--API网关-Kong
微服务·golang·kong
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 51. N 皇后 | C++ 回溯算法&状态数组
c++·算法·leetcode
梦想与想象-广州大智汇2 小时前
告别“内存刺客”!sync-canal-go:轻量mysql实时同步数据到Elasticsearch‌,clickhouse,redis
mysql·elasticsearch·golang·同步数据
脱氧核糖核酸__2 小时前
LeetCode热题100——41.缺失的第一个正数(题解+答案+要点)
数据结构·c++·算法·leetcode·哈希算法
脱氧核糖核酸__2 小时前
LeetCode热题100——73.矩阵置零(题目+题解+答案)
c++·算法·leetcode·矩阵
Mr_Xuhhh2 小时前
深入理解单链表的递归反转:从原理到实现
算法·leetcode·职场和发展
lolo大魔王2 小时前
Go语言的defer语句和Test功能测试函数
开发语言·后端·golang
lolo大魔王3 小时前
Go语言的结构体
开发语言·后端·golang