算法(TS):O(1) 时间插入、删除和获取随机元素

实现RandomizedSet 类:

  • RandomizedSet() 初始化 RandomizedSet 对象
  • bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false
  • bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false
  • int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。

你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1)

解法

利用一个 hash 表保存元素的下标,使 remove 方法的时间复杂度为 O(1)

ts 复制代码
class RandomizedSet {
    nums: number[] = []
    numIndexHash: Map<number,number> = new Map()
    constructor() {}

    insert(val: number): boolean {
        if(this.numIndexHash.has(val)) {
            return false
        }

        const index = this.nums.length
        this.nums.push(val)
        this.numIndexHash.set(val,index)
        return true
    }

    remove(val: number): boolean {
        if(!this.numIndexHash.has(val)) {
            return false
        }

        const index = this.numIndexHash.get(val),
                lastIndex = this.nums.length-1,
                lastVal = this.nums[lastIndex]

        this.nums[index] = lastVal
        this.numIndexHash.set(lastVal,index)
        this.nums.pop()
        this.numIndexHash.delete(val)
        
        return true
    }

    getRandom(): number {
        const index = Math.floor(Math.random() * this.nums.length)
        return this.nums[index]
    }
}
相关推荐
Trent19851 小时前
影楼精修-肤色统一算法解析
图像处理·人工智能·算法·计算机视觉
feifeigo1232 小时前
高光谱遥感图像处理之数据分类的fcm算法
图像处理·算法·分类
北上ing2 小时前
算法练习:19.JZ29 顺时针打印矩阵
算法·leetcode·矩阵
.格子衫.4 小时前
真题卷001——算法备赛
算法
XiaoyaoCarter4 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
Hygge-star4 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
June`5 小时前
专题二:二叉树的深度搜索(二叉树剪枝)
c++·算法·深度优先·剪枝
好吃的肘子7 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins
胡耀超7 小时前
霍夫圆变换全面解析(OpenCV)
人工智能·python·opencv·算法·计算机视觉·数据挖掘·数据安全
软行7 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展