0%

380. Insert Delete GetRandom O(1)

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. */
RandomizedSet() {
srand(time(NULL)); // 用时间做种子
}

/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (m.count(val)) return false;
m[val] = v.size(); // 用数组下标来把hashmap和数组联系起来
v.push_back(val);
return true;
}

/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (!m.count(val)) return false;
m[v.back()] = m[val]; // 删除的主要操作是把数组中待删除的数和数组最后一个数『交换』,所以要把最后一个数的下标改成待删除的数的下标
v[m[val]] = v.back(); // 把数组结尾的数挪到待删除的数的位置
v.pop_back();
m.erase(val);
return true;
}

/** Get a random element from the set. */
int getRandom() {
return v.empty() ? 0 : v[rand() % v.size()]; // 注意数组为空的case
}

unordered_map<int, int> m; // 因为添加删除都要O(1)所以肯定是unordered容器,又因为unordered_set无法保存更多的信息,所以肯定要想到用unordered_map
vector<int> v; // 因为需要random access所以肯定要用一个数组存所有的数,即v[m[val]] = val
};

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