leetcode_insert_delete_getrandom_O_1_duplicates_allowed

难度:Medium

使用unordered_multimap,或者map>。
unordered_multimap
priority_queue解法
priority_queue

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class RandomizedCollection {
public:
typedef std::unordered_multimap<int,int> intmap;
/** 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) {
// cout<<"insert: --------"<<val<<endl;
if(mm.count(val) == 0)
{
v.push_back(val);
mm.insert(pair<int,int>(val,v.size()-1));
return true;
}
else
{
v.push_back(val);
mm.insert(pair<int,int>(val,v.size()-1));
return false;
}
}

/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {

if(mm.count(val) == 0)
{
return false;
}
else
{
auto range = mm.equal_range(val);
auto one_val = range.first;
int val_pos = one_val->second;
if(val_pos == v.size()-1)
{
v.pop_back();
mm.erase(one_val);
return true;
}
else
{
int back = v.back();
int back_pos = v.size()-1;
v.pop_back();

auto back_range = mm.equal_range(back);
auto back_range_it = back_range.first;
for(; back_range_it != back_range.second;back_range_it++)
{
if(back_range_it->second == back_pos)
{
break;
}
}
mm.erase(one_val);
}


return true;
}
}

/** Get a random element from the collection. */
int getRandom() {
return v[rand()%v.size()];
}
unordered_multimap<int,int>mm;
vector<int>v;
};

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