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
}
相关推荐
lightqjx11 小时前
【算法】双指针
c++·算法·leetcode·双指针
sin_hielo11 小时前
leetcode 2147
数据结构·算法·leetcode
萌>__<新11 小时前
力扣打卡每日一题——缺失的第一个正数
数据结构·算法·leetcode
萌>__<新12 小时前
力扣打卡每日一题————零钱兑换
算法·leetcode·职场和发展
古城小栈12 小时前
Golang 中 return 与 defer 的 长幼尊卑
golang
重生之后端学习12 小时前
238. 除自身以外数组的乘积
java·数据结构·算法·leetcode·职场和发展·哈希算法
Learner__Q12 小时前
每天五分钟:动态规划-LeetCode高频题_day2
算法·leetcode·动态规划
teamlet14 小时前
Gear DNS - 一个go语言开发的小型dns系统
golang·dns·网络服务
Dream it possible!14 小时前
LeetCode 面试经典 150_字典树_添加与搜索单词 - 数据结构设计(96_211_C++_中等)
c++·leetcode·面试·字典树