算法(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]
    }
}
相关推荐
黄金龙PLUS18 分钟前
5个1024比特大状态置换算法的设计与分析
算法·网络安全·密码学·哈希算法·同态加密
心中有你021428 分钟前
C语言埃氏筛法(素数筛选)
c语言·数据结构·算法
Omics Pro2 小时前
Cell封面|衰老生物学开源AI工具包
数据库·人工智能·算法·机器学习·自然语言处理
用户0934077735142 小时前
HarmonyOS WPS Open SDK 实践:从 HAR 集成到 OpenFileRequest 最小闭环
typescript·harmonyos
FYKJ_20103 小时前
springboot雅集社区养老管理系统04456-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
FYKJ_20103 小时前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
javascript·vue.js·spring boot·mysql·typescript·spark·express
FYKJ_20103 小时前
springboot羽毛球场地管理系统00626-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
UIU1144 小时前
递归算法与汉诺塔
c++·学习·算法·c#·递归
FYKJ_20104 小时前
django药饮个性化推荐系统54839-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
濮水大叔9 小时前
Cabloy全栈框架的两个SSR入口:Vona集成式SSR vs Zova独立式SSR
typescript·node.js·全栈