【JS每日一算法:剑指Offer系列】🟨154.O(1) 时间插入、删除和获取随机元素(哈希表+栈)

63 阅读2分钟

实现RandomizedSet 类:

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

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

 

示例:

输入
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
输出
[null, true, false, true, 2, true, false, 2]

解释
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。

 

提示:

  • -231 <= val <= 231 - 1
  • 最多调用 insertremove 和 getRandom 函数 2 * ``105 次
  • 在调用 getRandom 方法时,数据结构中 至少存在一个 元素。

题解:

个人博客

更多JS版本题解点击链接关注该仓库👀

/**
 * 本方案使用map+array的方式,利用map实现插入/删除,并且
 * 满足O(1)的时间复杂度。而getRandom则利用数组,在插入元
 * 素时,同样在数组中插入相应的元素,并在map中记录插入的
 * 元素的索引。删除元素时,将数组尾部元素移动到删除的元素
 * 的位置,并改变该元素在map中的记录的索引,然后删除数组与
 * map中的元素
 */
var RandomizedSet = function () {
    this.list = [];
    this.map = new Map();
};
RandomizedSet.prototype.insert = function (val) {
    if (this.map.has(val)) return false
    this.map.set(val, this.list.length)
    this.list.push(val)
    return true
};
RandomizedSet.prototype.remove = function (val) {
    let index = this.map.get(val)
    if (index == undefined) return false
    this.list[index] = this.list[this.list.length - 1]
    this.map.set(this.list[index], index);
    this.list.pop();
    this.map.delete(val)
    return true
};
RandomizedSet.prototype.getRandom = function () {
    return this.list[Math.floor(Math.random() * this.list.length)];
};