算法(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]
    }
}
相关推荐
用户5671504710215 分钟前
OpenClaw 记忆管理系统技术文档
算法
9359627 分钟前
练习题53-60
算法·深度优先
霖大侠41 分钟前
Wavelet Meets Adam: Compressing Gradients forMemory-Efficient Training
人工智能·深度学习·算法·机器学习·transformer
AI成长日志1 小时前
【笔面试算法学习专栏】二分查找专题:力扣hot100经典题目深度解析
学习·算法·面试
lcreek1 小时前
流量优化之道:Ford-Fulkerson 最大流算法
算法·
垫脚摸太阳1 小时前
第 36 场 蓝桥·算法挑战赛·百校联赛---赛后复盘
数据结构·c++·算法
Aaswk1 小时前
刷题笔记(回溯算法)
数据结构·c++·笔记·算法·leetcode·深度优先·剪枝
NAGNIP2 小时前
一文搞懂CNN经典架构-ResNet!
算法·面试
计算机安禾2 小时前
【数据结构与算法】第14篇:队列(一):循环队列(顺序存储
c语言·开发语言·数据结构·c++·算法·visual studio
Frostnova丶2 小时前
(11)LeetCode 239. 滑动窗口最大值
数据结构·算法·leetcode