You need to enable JavaScript to run this app. 实现O(1)操作的RandomizedSet类返回undefined报错排查
优惠活动
大模型
产品
解决方案
定价
更多

实现O(1)操作的RandomizedSet类返回undefined报错排查

问题相关说明

本题要求实现RandomizedSet类,满足所有方法平均时间复杂度为O(1),类需要实现的接口如下:

  • RandomizedSet():初始化集合对象
  • bool insert(int val):当val不存在时插入集合,返回true;元素已存在则返回false
  • bool remove(int val):当val存在时从集合移除,返回true;元素不存在则返回false
  • int getRandom():等概率随机返回集合中一个元素,调用时保证集合非空
问题现象

给出的实现代码可通过部分测试用例,但部分场景下会返回undefined,无法定位根因,原实现代码如下:

var RandomizedSet = function() {
    this.map = new Map();
    this.vector = [];
};

/** 
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
    if(this.map.has(val)) return false;
    else {
        let position = 0;
        if(this.vector.length > 0)
            position = this.vector.length-1;
        
        this.map.set(val, position);
        this.vector.push(val);
        return true;
    }
};

/** 
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
    if(this.map.has(val)) {
        const index = this.map.get(val);
        const lastVal = this.vector[this.vector.length-1];
        this.vector[index] = lastVal;
        this.vector.pop();
        this.map.delete(val);
        return true;
    }else {
        return false;
    }
};

/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
    const randIndex = Math.floor(Math.random() * this.vector.length);
    return this.vector[randIndex];
};

/** 
* Your RandomizedSet object will be instantiated and called as such:
* var obj = new RandomizedSet()
* var param_1 = obj.insert(val)
* var param_2 = obj.remove(val)
* var param_3 = obj.getRandom()
*/
根因定位

代码共有两处逻辑错误:

  1. insert方法的元素索引计算错误
    新元素通过push操作添加到数组末尾,其正确索引为push操作前的数组长度。原代码在数组非空时,错误将数组长度-1(即数组最后一个已有元素的索引)赋值给新元素的position,导致map中存储的元素索引和数组实际位置从第二个插入的元素开始全部错位。
  2. remove方法缺少索引更新逻辑
    删除元素时,使用数组末尾元素覆盖待删除位置的思路符合O(1)时间要求,但原代码覆盖完成后,没有更新map中被移动的末尾元素对应的索引值,会导致map中存储的索引和数组实际位置不匹配;当后续操作访问到不存在的数组索引时,就会返回undefined。
修复后完整代码
var RandomizedSet = function() {
    this.map = new Map();
    this.vector = [];
};

/** 
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
    if(this.map.has(val)) return false;
    // 新元素插入到数组末尾,索引为push前的数组长度
    this.map.set(val, this.vector.length);
    this.vector.push(val);
    return true;
};

/** 
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
    if(!this.map.has(val)) return false;
    const index = this.map.get(val);
    const lastVal = this.vector[this.vector.length - 1];
    // 用末尾元素覆盖待删除位置
    this.vector[index] = lastVal;
    // 更新被移动的末尾元素在map中的索引
    this.map.set(lastVal, index);
    // 移除数组末尾元素
    this.vector.pop();
    // 删除待移除元素的映射
    this.map.delete(val);
    return true;
};

/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
    const randIndex = Math.floor(Math.random() * this.vector.length);
    return this.vector[randIndex];
};

内容的提问来源于stack exchange,提问作者Suhail Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 02:03:24