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
}
相关推荐
lvwangshu9 分钟前
P6534 [COCI 2015/2016 #1] UZASTOPNI 等差树列 题解
动态规划·图论·题解·性质题
ttwuai2 小时前
Go 后台附件迁到对象存储后,path、cdnUrl 和 tenant_id 怎么一起验?
开发语言·后端·golang
ttwuai3 小时前
Go 后台清空操作日志失败,权限和无 WHERE 删除怎么排查?
开发语言·后端·golang
gsls2008084 小时前
OpsKat封装MCP:用 Go 标准库把运维 CLI 变成 AI 的“手“
运维·人工智能·golang·mcp
土司大王4 小时前
LeetCode hot100——缺失的第一个正数
数据结构·算法·leetcode
Cccp.1235 小时前
【leetcode】(二)认识O(NlogN)的排序
算法·leetcode
鹿角片ljp6 小时前
LeetCode 56:合并区间复盘|从排序思维到 List<int[]> 的简洁写法
算法·leetcode·list
qq_339191146 小时前
go cpu占比高排查,cpu100%排查,go pprof cpu命令
开发语言·后端·golang
玖玥拾7 小时前
LeetCode 205 同构字符串
算法·leetcode
小翰生信8 小时前
转录组下游分析全流程:DESeq2 差异分析、GO/KEGG 富集与 GSEA 实战
数据库·矩阵·golang