Insert Delete GetRandom O(1)

1. 解析

题目大意,设计一个结构,可以在常数级时间内O(1)实现集合(无重复元素)的增加、删除、获取随机数

2. 分析

我最先想到的是hashset进行操作,写到getRandom函数,突然发现在O(1)时间复杂度范围内无法获取数组中的任意一个数值。参考@Grandyang博主的思路,若要在O(1)时间复杂度内根据指定索引返回随机数,vector结构无疑是最好。增加insert和返回随机数getRandom在O(1)时间复杂度内比较容易实现。为了在vector上实现时间复杂度为O(1)的删除,我们就得建立hashmap存储对应数值的索引表,即每次将原数组vector中的最后一个元素放置在删除元素的的位置上,然后在hashmap中重新建立最后一个元素和当前的索引,删除原来的索引即可。

例如: nums  = [2, 5, 4, 3]  index = { (2, 0), (5, 1), (4, 2), (3, 3) },删除元素 val = 5

取出nums中最后一个元素3,将其放在元素5的索引位置上,索引通过index中查找,即 nums = [2, 3, 4]。在index中更新3在nums当中的索引,即 index = { (2, 0), (4, 2), (3, 1) }

class RandomizedSet {
public:
    /** Initialize your data structure here. */
    RandomizedSet() {
        
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        if (index.count(val)) return false;   //当前元素存在数组当中
        nums.push_back(val);
        index[val] = nums.size() - 1; //建立索引表
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) { //O(1)时间复杂度的删除
        if (!index.count(val)) return false; //当前元素没有存在数组当中
        int num = nums.back();
        nums[index[val]] = num; //删除当前给定的元素
        index[num] = index[val]; //更新原数组最后一个元素的索引
        nums.pop_back();
        index.erase(val); //删除当前元素
        return true;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        return nums[rand() % nums.size()];
    }
private:
    vector<int> nums;
    unordered_map<int, int> index;
};

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

 [1]https://www.cnblogs.com/grandyang/p/5740864.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值