Insert Delete GetRandom O(1)

设计一个数据结构实现在平均 O(1) 的复杂度下执行以下所有的操作。

  • insert(val): 如果这个元素不在set中,则插入。

  • remove(val): 如果这个元素在set中,则从set中移除。

  • getRandom: 随机从set中返回一个元素。每一个元素返回的可能性必须相同。

样例

// 初始化空集set
RandomizedSet randomSet = new RandomizedSet();

// 1插入set中。返回正确因为1被成功插入
randomSet.insert(1);

// 返回错误因为2不在set中
randomSet.remove(2);

// 2插入set中,返回正确,set现在有[1,2]。
randomSet.insert(2);

// getRandom 应该随机的返回1或2。
randomSet.getRandom();

// 从set中移除1,返回正确。set现在有[2]。
randomSet.remove(1);

// 2已经在set中,返回错误。
randomSet.insert(2);

// 因为2是set中唯一的数字,所以getRandom总是返回2。
randomSet.getRandom();

输入测试数据 (每行一个参数)如何理解测试数据?

 

class RandomizedSet {
public:


    set<int> myset;
    vector<int> ret;
    set<int> myromve;
    RandomizedSet() {
        // do intialization if necessary
        srand((int)time(0));
    }

    /*
     * @param val: a value to the set
     * @return: true if the set did not already contain the specified element or false
     */
    bool insert(int val) {
        // write your code here
        if(myset.find(val) == myset.end())
        {
            myset.insert(val);
            ret.push_back(val);
            return true;
        }
        return false;
    }

    /*
     * @param val: a value from the set
     * @return: true if the set contained the specified element or false
     */
    bool remove(int val) 
    {
        // write your code here
        if(myset.find(val) == myset.end())
        {
            return false;
        }
        myset.erase(val);
        myromve.insert(val);
        return true;
    }

    /*
     * @return: Get a random element from the set
     */
    int getRandom() {
        // write your code here
        int size = ret.size();
        while(1)
        {
            int index = rand() % size;
            if(myromve.find(ret[index]) == myromve.end())
            {
                return ret[index];
            }
        }
        return 0;
        
    }
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * bool param = obj.insert(val);
 * bool param = obj.remove(val);
 * int param = obj.getRandom();
 */

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值