【算法】381. O(1) 时间插入、删除和获取随机元素 - 允许重复

本文介绍了一种数据结构设计,实现在平均时间复杂度为O(1)的插入、删除和随机获取操作,同时避免重复元素并支持指定范围内的随机选取。通过结合vector和unordered_map,实现高效且概率均匀的随机元素获取。
摘要由CSDN通过智能技术生成

设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。

注意: 允许出现重复元素。

insert(val):向集合中插入元素 val。
remove(val):当 val 存在时,从集合中移除一个 val。
getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。


集合本身用vector实现
额外用一个map保存,元素到它所有位置的映射

o1的删除实现是通过交换元素和数组的最后一个元素。
因为是随机获取元素,元素的位置并不重要。

有一说一,写完真的很爽

class RandomizedCollection {
public:
    //实际上与不允许重复的集合类似
    vector<int> vec;
    unordered_map<int, vector<int>> mp;
    /** Initialize your data structure here. */
    RandomizedCollection() {

    }
    
    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    bool insert(int val) {
        if(mp.count(val)) {
            mp[val].push_back(vec.size());
            vec.push_back(val);
            return 0;
        }
        vector<int> myvec(1, vec.size());    
        mp[val] = myvec;
        vec.push_back(val);
        return 1;
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        if(mp.count(val)) {
            int index = mp[val].back();
            int n = vec.size() - 1;
            for(int i = 0; i < mp[vec[n]].size(); ++i) {
                if(mp[vec[n]][i] == n) {
                    mp[vec[n]][i] = index;
                    break;
                }
            }
            swap(vec[index], vec[n]);
            vec.pop_back();
            mp[val].pop_back();
            if(mp[val].empty()) {
                mp.erase(val);
            }
            return 1;
        }
        return 0;
    }
    
    /** Get a random element from the collection. */
    int getRandom() {
        return vec[rand() % vec.size()];
    }
};

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

这道题属实不错,下面来看一道gg phone screen中的一道面试题
原题lc讨论链接
Question:
Implement a random number generator for numbers between [0, n]. Every time the generator function is called, you should return a random number. However, no repetitions are allowed (i.e. you cannot return the same number twice). Once you’ve used up all numbers, return 0.

One other follow up was that the generator could be given a range [start, end] and it should only return numbers between that range.

优质答复
这个评论给出的链接正是这道381

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值