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
}
相关推荐
sheeta19982 小时前
LeetCode 每日一题笔记 日期:2025.03.21 题目:3643.垂直翻转子矩阵
笔记·leetcode·矩阵
We་ct8 小时前
LeetCode 918. 环形子数组的最大和:两种解法详解
前端·数据结构·算法·leetcode·typescript·动态规划·取反
x_xbx10 小时前
LeetCode:83. 删除排序链表中的重复元素
算法·leetcode·链表
xsyaaaan13 小时前
leetcode-hot100-链表
leetcode·链表
逆境不可逃15 小时前
LeetCode 热题 100 之 33. 搜索旋转排序数组 153. 寻找旋转排序数组中的最小值 4. 寻找两个正序数组的中位数
java·开发语言·数据结构·算法·leetcode·职场和发展
leaves falling16 小时前
二分查找:迭代与递归实现全解析
数据结构·算法·leetcode
做怪小疯子16 小时前
Leetcode刷题——深度优先搜索(DFS)
算法·leetcode·深度优先
想吃火锅100518 小时前
【leetcode】105. 从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
圣保罗的大教堂18 小时前
leetcode 3567. 子矩阵的最小绝对差 中等
leetcode
老鼠只爱大米18 小时前
LeetCode经典算法面试题 #215:数组中的第K个最大元素(快速选择、堆排序、计数排序等多种实现方案详解)
算法·leetcode·堆排序·快速选择·topk·数组中的第k个最大元素