1+ /*
2+
3+ Insert Delete GetRandom O(1)
4+ ----------------------------
5+
6+ Design a data structure that supports all following operations in average O(1) time.
7+
8+ insert(val): Inserts an item val to the set if not already present.
9+ remove(val): Removes an item val from the set if present.
10+ getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
11+ Example:
12+
13+ // Init an empty set.
14+ RandomizedSet randomSet = new RandomizedSet();
15+
16+ // Inserts 1 to the set. Returns true as 1 was inserted successfully.
17+ randomSet.insert(1);
18+
19+ // Returns false as 2 does not exist in the set.
20+ randomSet.remove(2);
21+
22+ // Inserts 2 to the set, returns true. Set now contains [1,2].
23+ randomSet.insert(2);
24+
25+ // getRandom should return either 1 or 2 randomly.
26+ randomSet.getRandom();
27+
28+ // Removes 1 from the set, returns true. Set now contains [2].
29+ randomSet.remove(1);
30+
31+ // 2 was already in the set, so return false.
32+ randomSet.insert(2);
33+
34+ // Since 2 is the only number in the set, getRandom always return 2.
35+ randomSet.getRandom();
36+ */
37+
38+ class RandomizedSet {
39+ public:
40+ /* * Initialize your data structure here. */
41+ vector<int >arr;
42+ map<int , int >mp;
43+ RandomizedSet () {
44+
45+ }
46+
47+ /* * Inserts a value to the set. Returns true if the set did not already contain the specified element. */
48+ bool insert (int val) {
49+ if (mp.count (val)) return false ;
50+ mp[val] = arr.size ();
51+ arr.push_back (val);
52+ return true ;
53+ }
54+
55+ /* * Removes a value from the set. Returns true if the set contained the specified element. */
56+ bool remove (int val) {
57+ if (!mp.count (val)) return false ;
58+ int index = mp.at (val);
59+ mp[arr.back ()] = index;
60+ mp.erase (val);
61+ swap (arr[index], arr.back ());
62+ arr.pop_back ();
63+ return true ;
64+ }
65+
66+ /* * Get a random element from the set. */
67+ int getRandom () {
68+ int index = rand () % arr.size ();
69+ return arr[index];
70+ }
71+ };
72+
73+ /* *
74+ * Your RandomizedSet object will be instantiated and called as such:
75+ * RandomizedSet* obj = new RandomizedSet();
76+ * bool param_1 = obj->insert(val);
77+ * bool param_2 = obj->remove(val);
78+ * int param_3 = obj->getRandom();
79+ */
0 commit comments