380.时间插入、删除和获取随机元素

题目

实现RandomizedSet 类:

  • RandomizedSet() 初始化 RandomizedSet 对象
  • bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false
  • bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false
  • int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。

你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1)

示例:

输入
[“RandomizedSet”, “insert”, “remove”, “insert”, “getRandom”, “remove”, “insert”, “getRandom”]
[[], [1], [2], [2], [], [1], [2], []]
输出
[null, true, false, true, 2, true, false, 2]

解释
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。

提示:

  • -231 <= val <= 231 - 1
  • 最多调用 insertremovegetRandom 函数 2 * ``105
  • 在调用 getRandom 方法时,数据结构中 至少存在一个 元素。

    思路

    一个vector保存所有的key。一个map保存key和在vector中对应的下标。
    插入:在vector中加入该值,在map中加入<该值,下标>
    随机获得:生成随机数在vector中获取一个。
    删除:
    vector最后一个元素key放到val的位置上:vector的val对应的位置设置为key,哈希表的key键对应的位置设置为val的值,之后分别删除vector的最后一个元素和哈希表的val元素即可。

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    class RandomizedSet {
    public:
    /** Initialize your data structure here. */
    unordered_map<int,int> m;
    vector<int> keys;
    RandomizedSet() {

    }

    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
    if(m.find(val)!=m.end()) return false;
    keys.push_back(val);
    m[val] = keys.size()-1;
    return true;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
    if(m.find(val)==m.end()) return false;
    int temp = keys[keys.size()-1];
    m[temp] = m[val];
    keys[m[temp]] = temp;
    keys.pop_back();
    m.erase(val);
    return true;
    }

    /** Get a random element from the set. */
    int getRandom() {
    return keys[rand()%keys.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();
    */

381.时间插入、删除和获取随机元素-允许重复

题目

设计一个支持在平均 时间复杂度 O(1) 执行以下操作的数据结构。

注意: 允许出现重复元素。

  1. insert(val):向集合中插入元素 val。
  2. remove(val):当 val 存在时,从集合中移除一个 val。
  3. getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。

示例:

// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();

// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);

// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);

// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
collection.insert(2);

// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();

// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
collection.remove(1);

// getRandom 应有相同概率返回 1 和 2 。
collection.getRandom();

思路

用一个vector保存所有的键。
用一个哈希表保存键和对应的在vector的下标。
插入:在键对应的下标中加入一个
随机获得:生成随机数在vector中获取一个。
删除:
将vector最后一个元素key取出来,key对应的下标end也取出来。
首先把要删除val的元素在vector中的一个位置idx赋给key,之后在哈希表key的下标中删除end,添加上val的下标idx。从val的下标中删除idx即可。
**这里不太明白的事为什么要有if(idx<end) m[keys[idx]].emplace(idx)一句,如果这句换了位置就不对了,一直没明白`

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class RandomizedCollection {
public:
unordered_map<int,unordered_set<int>> m;
vector<int> keys;

/** 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) {
keys.push_back(val);
if(m.find(val)==m.end()){
m[val].emplace(int(keys.size()-1));
return true;
}else{
m[val].emplace(int(keys.size()-1));
return false;
}
}

/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if(m.find(val)==m.end()) return false;
//取得最后一个key对应的下标end,要删除的元素所有下标的第一个
int end = keys.size() - 1;
int idx = *m[val].begin();
//最后一个key赋值到要删除的位置上,并且最后一个key要删除end这个下标。
keys[idx] = keys.back();
m[keys[idx]].erase(end);
//要删除的元素删除一个下标,如果是最后一个,就把元素从哈细表中删除。
m[val].erase(idx);
if(m[val].empty()) m.erase(val);
//如果删除元素的下标不是最后一个,就把删除的下标赋给原来最后一个key。
if(idx<end) m[keys[idx]].emplace(idx);

keys.pop_back();
return true;
}

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

/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection* obj = new RandomizedCollection();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/