LeetCode每日一题-O(1) 时间插入、删除和获取随机元素 - 允许重复

O(1) 时间插入、删除和获取随机元素 - 允许重复

这里是引用

// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();

// 向集合中插入 1 。返回 true 表示集合不包含 1 。 collection.insert(1);

// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);

// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。 collection.insert(2);

// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。 collection.getRandom();

// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。 collection.remove(1);

// getRandom 应有相同概率返回 1 和 2 。 collection.getRandom();

class RandomizedCollection {
public:
    /** 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) {
        vec_.push_back(val);                        //存储起来 - 统计概率问题
        ump_[val].insert(vec_.size() - 1);          //这样写太棒了 - 解决下标问题
        return ump_[val].size() == 1;          
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        auto it = ump_.find(val);
        if(it == ump_.end()) {
            return false;                           //不存在
        }
        int index  = *(it->second.begin());         //取到val值set集合中一个下标
        vec_[index] = vec_.back();                  //交换最后一个元素

        ump_[vec_[index]].erase(vec_.size()-1);     //删除back()-->set集合中最后位置
        it->second.erase(index);                    //删除val-->set集合中index
        if(index < vec_.size() - 1) {               //防止删除最后一个元素 - 重复添加
            ump_[vec_[index]].insert(index);
        }
        if(it->second.size() == 0) {
            ump_.erase(val);
        }
        vec_.pop_back(); 
        return true;
    }
    
    /** Get a random element from the collection. */
    int getRandom() {
        return vec_[rand() % vec_.size()];
    }

private:
    unordered_map<int, unordered_set<int>>  ump_;
    vector<int> vec_;
};

/**
 * 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();
 */

如果写过LRU缓存算法 - 借鉴下规律就会发现不难。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值