Leetcode 380 - Insert Delete GetRandom O(1)

24 篇文章 0 订阅
8 篇文章 0 订阅

题意

设计一个数结构,支持:

  1. insert(x) O(1) 插入元素x,如果已经存在返回false
  2. remove(x) O(1) 删除元素x,如果x不存在返回false
  3. getRandom() O(1) 的等概率从里面随机返回一个元素

思路

unordered_map支持 O(1) 插入和删除,只需要 O(1) 的随机返回元素。

我们用一个数组映射一下,用arr[pos] = x表示位置pos上是元素x。

我们用unordered_maphas来表示hashmap,并且has[x] = pos代表元素x在数组arr的位置为pos。

于是:

  1. insert(x):将元素x插入到unordered_map的has里面,用has[x] = pos表示元素x在数组arr的位置在pos上。于是,插入时需要:
    1. has[x] = pos
    2. arr[pos] = x
  2. remove(x):从has里面找到x的迭代器,并且has[x] = pos。于是:
    1. 删除迭代器
    2. 将arr[pos]上需要删除的那个数和arr最后一个数字交换位置,达到删除的效果。
  3. getRandom():返回arr[rand() % n]

代码

const int maxn = 100005;

class RandomizedSet {
private:
    int size;
    unordered_map<int, int> has;
    int arr[maxn];
public:
    /** Initialize your data structure here. */
    RandomizedSet() {
        size = 0;
        has.clear();
    }

    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        if (!has.count(val)) {
            has[val] = size;
            arr[size++] = val;
            return true;
        }
        return false;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        auto it = has.find(val);
        if (it != has.end()) {
            int pos = it->second;
            has.erase(it);
            swap(arr[pos], arr[--size]);
            auto final = has.find(arr[pos]);
            if (final != has.end()) final->second = pos;
            return true;
        }
        return false;
    }

    /** Get a random element from the set. */
    int getRandom() {
        return arr[rand() % size];
    }
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * bool param_1 = obj.insert(val);
 * bool param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值