381. Insert Delete GetRandom O(1) - Duplicates allowed - Hard

本文介绍了一种支持插入、删除和随机获取元素操作,且平均时间复杂度为O(1)的数据结构实现。通过使用HashMap和ArrayList,确保了即使存在重复元素,也能高效地进行操作。文章详细解释了insert、remove和getRandom方法的具体实现,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Design a data structure that supports all following operations in average O(1) time.

Note: Duplicate elements are allowed.

 

  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

 

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

 

380. Insert Delete GetRandom O(1) - Medium 的 follow-up

还是用hashmap和arraylist,hashmap中存<val, [val indices]>, arraylist中存 (val, index in hashmap),即 (val, val在map.get(val)中对应的下标)

insert: 直接加在hash map对应的list末尾和arraylist的末尾

delete: 和最后一个元素交换,再删除最后一个元素。注意如果map.get(val)只有一个元素的时候,要把map中对应的val删除

class RandomizedCollection {
    Map<Integer, List<Integer>> map;
    List<int[]> list;
    Random r;

    /** Initialize your data structure here. */
    public RandomizedCollection() {
        map = new HashMap<>();
        list = new ArrayList<>();
        r = new Random();
    }
    
    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    public boolean insert(int val) {
        if(map.containsKey(val)) {
            int idx = map.get(val).size() - 1;
            list.add(new int[] {val, idx + 1});
            map.get(val).add(list.size() - 1);
            return false;
        }
        else {
            list.add(new int[] {val, 0});
            map.put(val, new ArrayList<>());
            map.get(val).add(list.size() - 1);
            return true;
        }
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    public boolean remove(int val) {
        if(!map.containsKey(val)) {
            return false;
        }
        List<Integer> idxs = map.get(val);
        int idx = idxs.get(idxs.size() - 1);
        if(idxs.size() == 1) {
            int[] last = list.get(list.size() - 1);
            list.set(idx, last);
            list.remove(list.size() - 1);
            List<Integer> last_idxs = map.get(last[0]);
            last_idxs.set(last[1], idx);
            map.remove(val);
            return true;
        }
        if(idx < list.size() - 1) {
            int[] last = list.get(list.size() - 1);
            list.set(idx, last);
            List<Integer> last_idxs = map.get(last[0]);
            last_idxs.set(last[1], idx);
        }
        list.remove(list.size() - 1);
        List<Integer> tmp = map.get(val);
        tmp.remove(tmp.size() - 1);
        
        return true;
    }
    
    /** Get a random element from the collection. */
    public int getRandom() {
        return list.get(r.nextInt(list.size()))[0];
    }
}

/**
 * Your RandomizedCollection object will be instantiated and called as such:
 * RandomizedCollection obj = new RandomizedCollection();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */

 

转载于:https://www.cnblogs.com/fatttcat/p/10214480.html

<think>我们正在解决一个Rust编程问题:在使用`getrandom`库时,针对`wasm*-unknown-unknown`目标平台出现不支持的问题,错误提示建议启用`js`特性。 根据错误信息,我们需要在`getrandom`库中启用`js`特性来支持wasm目标。 步骤: 1. 在Cargo.toml文件中,为`getrandom`依赖添加`features = ["js"]`。 2. 或者,在代码中通过特性标志来启用。 但是,我们需要注意的是,`wasm32-unknown-unknown`目标平台默认不提供随机数源,因此需要依赖浏览器提供的`crypto.getRandomValues`方法,而`getrandom`库的`js`特性正是用来启用这个功能的。 另外,参考引用[2]中提到的问题是关于emscripten和原子操作的,但我们的问题与随机数生成有关,所以主要关注`getrandom`库的解决方案。 因此,我们修改Cargo.toml如下: ```toml [dependencies] getrandom = { version = "0.2", features = ["js"] } ``` 如果已经存在`getrandom`依赖,则只需添加特性。 如果项目是一个库,并且希望保持与wasm的兼容性,可能还需要考虑条件编译,但通常直接启用`js`特性即可。 注意:在非wasm目标上启用`js`特性不会有影响,因为该特性只对wasm目标有效。 如果问题仍然存在,可能需要检查是否同时存在多个版本的`getrandom`,或者是否有其他依赖覆盖了特性设置。 另外,确保使用的`getrandom`版本至少是0.2.0,因为`js`特性是在这个版本中引入的。 如果使用`wasm-bindgen`,还需要确保在项目中包含了`wasm-bindgen`和`web-sys`(因为`getrandom`的`js`特性依赖于`web-sys`来调用浏览器API)。但是,`getrandom`的`js`特性已经处理了这些依赖,所以只需要在Cargo.toml中正确声明即可。 因此,总结解决方案:在Cargo.toml中为`getrandom`添加`js`特性。 下面我们将这个解决方案以清晰的步骤展示给用户。</think>### Rust `getrandom`库在 wasm*-unknown-unknown 目标下的解决方案 针对 `getrandom` 库在 wasm*-unknown-unknown 目标平台报错的问题,核心解决方案是启用 `js` 特性。以下是具体步骤: #### 解决方法 1. **修改 Cargo.toml 依赖** 在项目的 `Cargo.toml` 文件中,为 `getrandom` 添加 `js` 特性: ```toml [dependencies] getrandom = { version = "0.2", features = ["js"] } ``` 这会使 `getrandom` 使用浏览器的 `crypto.getRandomValues()` API 作为随机源[^1]。 2. **确保 wasm 工具链正确安装** 运行以下命令安装 wasm 目标: ```bash rustup target add wasm32-unknown-unknown ``` 并验证工具链路径: ```bash rustc --print sysroot # 确认输出路径包含 wasm32-unknown-unknown 目录 ``` 3. **添加必要的 JavaScript 接口** 在 HTML 中加载 wasm 时,需确保浏览器支持: ```html <script> if (!window.crypto) window.crypto = { getRandomValues: (arr) => { for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256) } }; </script> ``` #### 原理说明 - wasm*-unknown-unknown 目标默认**不包含操作系统级随机源** - `js` 特性通过以下方式实现: 1. 编译时注入 `#[cfg(target_arch = "wasm32")]` 条件 2. 运行时调用 `crypto.getRandomValues()` Web API 3. 回退到 `Math.random()`(安全性较低) #### 验证步骤 ```bash cargo build --target wasm32-unknown-unknown wasm-bindgen target/wasm32-unknown-unknown/debug/your_crate.wasm --out-dir ./dist ``` 在浏览器加载生成的 JS/WASM 文件应不再报错。 #### 备选方案 如果仍需原子操作支持,可改用 `wasm32-wasi` 目标: ```bash rustup target add wasm32-wasi cargo build --target wasm32-wasi ``` 此目标提供完整的系统调用支持,但需要 WASI 运行时环境[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值