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
}
相关推荐
LYFlied1 分钟前
【每日算法】LeetCode 739. 每日温度:从暴力遍历到单调栈的优雅解决
前端·算法·leetcode·面试·职场和发展
yaoh.wang3 分钟前
力扣(LeetCode) 67: 二进制求和 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
夏鹏今天学习了吗10 分钟前
【LeetCode热题100(74/100)】跳跃游戏
算法·leetcode·游戏
小年糕是糕手20 分钟前
【C++】string类(二)
开发语言·数据结构·c++·程序人生·算法·leetcode·数字货币
周杰伦_Jay24 分钟前
【Go语言面试题核心详细解析】基础语法、并发编程、内存管理、接口、错误处理
开发语言·后端·golang
Tisfy24 分钟前
LeetCode 3573.买卖股票的最佳时机 V:深度优先搜索
算法·leetcode·深度优先
yaoh.wang26 分钟前
力扣(LeetCode) 58: 最后一个单词的长度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
LYFlied34 分钟前
【每日算法】LeetCode239. 滑动窗口最大值
数据结构·算法·leetcode·面试
Clarence Liu37 分钟前
Golang slice 深度原理与面试指南
开发语言·后端·golang
moxiaoran575338 分钟前
Go语言中的切片
golang