<leetcode>381. Insert Delete GetRandom O(1) - Duplicates allowed

381. Insert Delete GetRandom O(1) - Duplicates allowed

Design a data structure that supports all following operations inaverage O(1) time.

Note: Duplicate elements are allowed

  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:

// Init an empty collection.

RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.

collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].

collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].

collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.

collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].

collection.remove(1);

// getRandom should return 1 and 2 both equally likely.

collection.getRandom();

题目解释:设计一个数据结构,实现O(1)时间完成插入(insert),删除(remove)元素的功能

(1)insert(val):对数组集合进行insert,若集合已存在val,进行insert后返回false,若不存在,insert后返回true

(2)remove(val):对数字进行remove操作,若val不存在,返回false,若val存在,则进行remove后返回true

(3)getRandom:随机返回集合一个元素,使得返回元素的全部概率是一样的。

解题思路:

(1)要求O(1)时间内完成insert和remove操作,那么得放弃使用循环遍历搜索的操作

(2)考虑到集合的大小不固定,可以使用vector来存放集合

(3)为了能够实现快速insert和remove,这个时候需要一个unordered_map这种关联容器来存放集合元素序号。这是因为,只要知道了要操作的val,就能得到val值在集合vector中所处的位置索引, 为unordered_map[val]

#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
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) {
        v.push_back(val);
        Map[val].insert(v.size()-1); // 将val在v中的序号存在Map[val]中
        return Map[val].size() == 1; // 若等于1说明insert之前没有val这个值
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        if(Map[val].size() == 0 || Map.find(val) == Map.end()) return false;
        if (v.back() == val) {
//            Map[val].erase(Map[val].find(v.size()-1));
            Map[val].erase(v.size()-1);
            v.pop_back();
        }
        else{
            int index = *Map[val].begin();  // index是待remove元素在vector中的位置索引
            Map[val].erase(index);
            swap(v[index],v[v.size()-1]);
            v.pop_back();
//            Map[v[index]].erase(Map[v[index]].find(v.size()));
            Map[v[index]].erase(v.size());
            Map[v[index]].insert(index);
            
        }
        return true;
    }
    
    /** Get a random element from the collection. */
    int getRandom() {
        return v[rand()%v.size()];
    }
    void printCollection(){
        for (int i = 0; i < v.size(); i++) {
            cout << v[i] << endl;
        }
    }
private:
    unordered_map<int, unordered_set<unsigned long> > Map;
    vector<int> v;
};
int main(int argc, const char * argv[]) {
    // insert code here...
    RandomizedCollection *collection = new RandomizedCollection();
    bool b1 = collection->insert(1);
    bool b2 = collection->insert(2);
//    bool b3 = collection->remove(1);
//    cout << b1 << " " << b2 << " " << b3 << endl;
    collection->printCollection();
    
    return 0;
}

leetcode上380题跟上面的381题不同的地方是:380要求集合里面没有重复出现的元素,而381允许有重复出现的元素。因此在完成380题的时候,只需要修改insert,确保collection里面没有重复的元素。380题的insert方法代码如下:

    bool insert(int val) {
        if(Map[val].size() == 0){
            v.push_back(val);
            Map[val].insert(v.size()-1);
            return true;
        }
        else return false;
    }


附录(C++)

1.关于unordered_set和unordered_map

unordered_map和unordered_set是无序关联容器,这些容器不是使用比较运算符来组织元素的,而是使用一个哈希函数和关键字类型的==运算符。无序容器也有与有序容器一样的操作(find,insert等)

2.关于unordered_map.find()的使用方法

unordered_map.find(val)

这个方法是查找unordered_map容器里面的val值,若存在则返回迭代器iterate,否则会返回unordered_map.end()的迭代器

3.关于unordered_set的erase方法

unordered_set.erase(), 括号中可以是元素的值,也可以是迭代器。所以代码中以下2行是等价的:

Map[v[index]].erase(Map[v[index]].find(v.size()));
Map[v[index]].erase(v.size());

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值