leetcode刷题.381. O(1) 时间插入、删除和获取随机元素 - 允许重复。每日打卡

代码:

class RandomizedCollection381_hard {
public:
        /** Initialize your data structure here. */
        RandomizedCollection381_hard() {

        }

        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        bool insert(int val) {

                elem_list_.push_back(val);
                elem_map_[val].insert(elem_list_.size() - 1);
                return (elem_map_[val].size() == 1);
        }

        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        bool remove(int val) {

                if (elem_map_.find(val) == elem_map_.end())
                        return false;

                int idx = *(elem_map_[val].begin());
                elem_list_[idx] = elem_list_.back();
                elem_map_[val].erase(idx);

                /* 交换元素后需要更新被交换元素位置信息 */
                elem_map_[elem_list_[idx]].erase(elem_list_.size() - 1);
                /* 如果删除的是最末端元素,则直接删除 */
                if (idx < elem_list_.size() - 1) {
                        elem_map_[elem_list_[idx]].insert(idx);
                }
                /* 在该元素结合为空的时候删除该元素的映射项 */
                if (elem_map_[val].empty()) {
                        elem_map_.erase(val);
                }
                elem_list_.pop_back();
                return true;
        }

        /** Get a random element from the collection. */
        int getRandom() {
                return elem_list_[rand() % elem_list_.size()];
        }
private:
        vector<int> elem_list_;
        unordered_map<int, unordered_set<int>> elem_map_;
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值