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
}
相关推荐
前端小白在前进1 小时前
力扣刷题:复原IP地址
tcp/ip·算法·leetcode
yaoh.wang1 小时前
力扣(LeetCode) 94: 二叉树的中序遍历 - 解法思路
python·算法·leetcode·面试·职场和发展·二叉树·跳槽
资深web全栈开发1 小时前
并查集(Union-Find)套路详解
leetcode·golang·并查集·unionfind
努力学算法的蒟蒻1 小时前
day39(12.20)——leetcode面试经典150
算法·leetcode·面试
阿昭L2 小时前
leetcode链表是否有环
算法·leetcode·链表
yaoh.wang2 小时前
力扣(LeetCode) 83: 删除排序链表中的重复元素 - 解法思路
程序人生·算法·leetcode·链表·面试·职场和发展
阿昭L2 小时前
leetcode旋转链表
算法·leetcode·链表
im_AMBER2 小时前
Leetcode 81 【滑动窗口(定长)】
数据结构·笔记·学习·算法·leetcode
Swift社区3 小时前
LeetCode 452 - 用最少数量的箭引爆气球
算法·leetcode·职场和发展
yaoh.wang3 小时前
力扣(LeetCode) 70: 爬楼梯 - 解法思路
python·算法·leetcode·面试·职场和发展·动态规划·递归