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];
}
};
|
'C' 카테고리의 다른 글
c++ leetcode 939 minimum rectangle area o(n^2) solution code (0) | 2021.07.24 |
---|---|
c++ leetcode 525 contiguous array solution (0) | 2021.07.24 |
c++ leetcode top-k frequent elements O(nlogn) solution (0) | 2021.07.16 |
c++ leetcode top k frequent words (sort and custom comparison) solution (0) | 2021.07.16 |
c++ leetcode 290 word pattern with double hashmap(100% faster) solution (0) | 2021.07.16 |