C
c++ leetcode 380 Insert Delete GetRandom o(1) solution code
데브웅
2021. 7. 17. 01:39
code >>
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
|
class RandomizedSet {
public:
/** Initialize your data structure here. */
unordered_map<int, int> hashmap;
vector<int> intarray;
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (hashmap.count(val) == 0)
{
intarray.emplace_back(val);
hashmap[val] = (int)intarray.size()-1;
return true;
}
else
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (hashmap.count(val) == 0)
return false;
else
{
int idx = hashmap[val];
intarray[idx] = intarray.back();
hashmap[intarray[idx]] = idx;
intarray.pop_back();
hashmap.erase(val);
}
return true;
}
/** Get a random element from the set. */
int getRandom() {
int sizeArray = (int)intarray.size();
//cout << "size of array : " << sizeArray << endl;
int ran_num = rand() % sizeArray;
//cout << "ran num : " << ran_num << endl;
return intarray[ran_num];
}
};
|