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
}
相关推荐
踩坑记录2 小时前
leetcode hot100 2.两数相加 链表 medium
leetcode·链表
历程里程碑4 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
TracyCoder1236 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
放荡不羁的野指针7 小时前
leetcode150题-滑动窗口
数据结构·算法·leetcode
女王大人万岁8 小时前
Go标准库 io与os库详解
服务器·开发语言·后端·golang
TracyCoder1238 小时前
LeetCode Hot100(13/100)——238. 除了自身以外数组的乘积
算法·leetcode
Anastasiozzzz8 小时前
LeetCode Hot100 215. 数组中的第K个最大元素
数据结构·算法·leetcode
让我上个超影吧8 小时前
【力扣76】最小覆盖子串
算法·leetcode·职场和发展
求梦8209 小时前
【力扣hot100题】合并两个有序链表(22)
算法·leetcode·链表
女王大人万岁10 小时前
Go语言time库核心用法与实战避坑
服务器·开发语言·后端·golang