算法(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]
    }
}
相关推荐
鑫—萍19 分钟前
C/C++精品算法——双指针(1)
c语言·c++·算法
铭哥的编程日记27 分钟前
深入浅出蓝桥杯:算法基础概念与实战应用(三)搜索
算法·蓝桥杯·深度优先
2501_9411118929 分钟前
低延迟系统C++优化
开发语言·c++·算法
2501_941111991 小时前
C++中的装饰器模式变体
开发语言·c++·算法
Espresso Macchiato2 小时前
Leetcode 3748. Count Stable Subarrays
算法·leetcode·职场和发展·leetcode hard·leetcode 3748·leetcode周赛476·区间求和
大袁同学2 小时前
【哈希hash】:程序的“魔法索引”,实现数据瞬移
数据结构·c++·算法·哈希算法·散列表
一水鉴天2 小时前
整体设计 全面梳理复盘 之39 生态工具链 到顶级表征及其完全公理化
大数据·人工智能·算法
Moonbit2 小时前
入围名单公布|2025 MGPIC 决赛即将拉开帷幕!
后端·算法
2501_941112613 小时前
C++与Docker集成开发
开发语言·c++·算法