Skip to content

Commit 05b2420

Browse files
committed
feat: solve No.380,381
1 parent 31b6ad6 commit 05b2420

File tree

2 files changed

+260
-0
lines changed

2 files changed

+260
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# 380. Insert Delete GetRandom O(1)
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Array, Hash Table, Math, Design, Randomized.
5+
- Similar Questions: Insert Delete GetRandom O(1) - Duplicates allowed.
6+
7+
## Problem
8+
9+
Implement the `RandomizedSet` class:
10+
11+
12+
13+
- `RandomizedSet()` Initializes the `RandomizedSet` object.
14+
15+
- `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
16+
17+
- `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
18+
19+
- `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
20+
21+
22+
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
23+
24+
 
25+
Example 1:
26+
27+
```
28+
Input
29+
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
30+
[[], [1], [2], [2], [], [1], [2], []]
31+
Output
32+
[null, true, false, true, 2, true, false, 2]
33+
34+
Explanation
35+
RandomizedSet randomizedSet = new RandomizedSet();
36+
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
37+
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
38+
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
39+
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
40+
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
41+
randomizedSet.insert(2); // 2 was already in the set, so return false.
42+
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
43+
```
44+
45+
 
46+
**Constraints:**
47+
48+
49+
50+
- `-231 <= val <= 231 - 1`
51+
52+
- At most `2 * ``105` calls will be made to `insert`, `remove`, and `getRandom`.
53+
54+
- There will be **at least one** element in the data structure when `getRandom` is called.
55+
56+
57+
58+
## Solution
59+
60+
```javascript
61+
62+
var RandomizedSet = function() {
63+
this.map = {};
64+
this.arr = [];
65+
};
66+
67+
/**
68+
* @param {number} val
69+
* @return {boolean}
70+
*/
71+
RandomizedSet.prototype.insert = function(val) {
72+
if (this.map[val] === undefined) {
73+
this.map[val] = this.arr.length;
74+
this.arr.push(val);
75+
return true;
76+
}
77+
return false;
78+
};
79+
80+
/**
81+
* @param {number} val
82+
* @return {boolean}
83+
*/
84+
RandomizedSet.prototype.remove = function(val) {
85+
if (this.map[val] !== undefined) {
86+
var delIndex = this.map[val];
87+
var lastVal = this.arr.pop();
88+
if (delIndex < this.arr.length) {
89+
this.arr[delIndex] = lastVal;
90+
this.map[lastVal] = delIndex;
91+
}
92+
delete this.map[val];
93+
return true;
94+
}
95+
return false;
96+
};
97+
98+
/**
99+
* @return {number}
100+
*/
101+
RandomizedSet.prototype.getRandom = function() {
102+
const num = Math.floor(Math.random() * this.arr.length);
103+
return this.arr[num];
104+
};
105+
106+
/**
107+
* Your RandomizedSet object will be instantiated and called as such:
108+
* var obj = new RandomizedSet()
109+
* var param_1 = obj.insert(val)
110+
* var param_2 = obj.remove(val)
111+
* var param_3 = obj.getRandom()
112+
*/
113+
```
114+
115+
**Explain:**
116+
117+
nope.
118+
119+
**Complexity:**
120+
121+
* Time complexity : O(1).
122+
* Space complexity : O(n).
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
# 381. Insert Delete GetRandom O(1) - Duplicates allowed
2+
3+
- Difficulty: Hard.
4+
- Related Topics: Array, Hash Table, Math, Design, Randomized.
5+
- Similar Questions: Insert Delete GetRandom O(1).
6+
7+
## Problem
8+
9+
`RandomizedCollection` is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.
10+
11+
Implement the `RandomizedCollection` class:
12+
13+
14+
15+
- `RandomizedCollection()` Initializes the empty `RandomizedCollection` object.
16+
17+
- `bool insert(int val)` Inserts an item `val` into the multiset, even if the item is already present. Returns `true` if the item is not present, `false` otherwise.
18+
19+
- `bool remove(int val)` Removes an item `val` from the multiset if present. Returns `true` if the item is present, `false` otherwise. Note that if `val` has multiple occurrences in the multiset, we only remove one of them.
20+
21+
- `int getRandom()` Returns a random element from the current multiset of elements. The probability of each element being returned is **linearly related** to the number of the same values the multiset contains.
22+
23+
24+
You must implement the functions of the class such that each function works on **average** `O(1)` time complexity.
25+
26+
**Note:** The test cases are generated such that `getRandom` will only be called if there is **at least one** item in the `RandomizedCollection`.
27+
28+
 
29+
Example 1:
30+
31+
```
32+
Input
33+
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]
34+
[[], [1], [1], [2], [], [1], []]
35+
Output
36+
[null, true, false, true, 2, true, 1]
37+
38+
Explanation
39+
RandomizedCollection randomizedCollection = new RandomizedCollection();
40+
randomizedCollection.insert(1); // return true since the collection does not contain 1.
41+
// Inserts 1 into the collection.
42+
randomizedCollection.insert(1); // return false since the collection contains 1.
43+
// Inserts another 1 into the collection. Collection now contains [1,1].
44+
randomizedCollection.insert(2); // return true since the collection does not contain 2.
45+
// Inserts 2 into the collection. Collection now contains [1,1,2].
46+
randomizedCollection.getRandom(); // getRandom should:
47+
// - return 1 with probability 2/3, or
48+
// - return 2 with probability 1/3.
49+
randomizedCollection.remove(1); // return true since the collection contains 1.
50+
// Removes 1 from the collection. Collection now contains [1,2].
51+
randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.
52+
```
53+
54+
 
55+
**Constraints:**
56+
57+
58+
59+
- `-231 <= val <= 231 - 1`
60+
61+
- At most `2 * 105` calls **in total** will be made to `insert`, `remove`, and `getRandom`.
62+
63+
- There will be **at least one** element in the data structure when `getRandom` is called.
64+
65+
66+
67+
## Solution
68+
69+
```javascript
70+
71+
var RandomizedCollection = function() {
72+
this.map = {};
73+
this.arr = [];
74+
};
75+
76+
/**
77+
* @param {number} val
78+
* @return {boolean}
79+
*/
80+
RandomizedCollection.prototype.insert = function(val) {
81+
var notFound = this.map[val] === undefined;
82+
if (notFound) this.map[val] = { arr: [], map: {} };
83+
this.map[val].map[this.arr.length] = this.map[val].arr.length;
84+
this.map[val].arr.push(this.arr.length);
85+
this.arr.push(val);
86+
return notFound;
87+
};
88+
89+
/**
90+
* @param {number} val
91+
* @return {boolean}
92+
*/
93+
RandomizedCollection.prototype.remove = function(val) {
94+
if (this.map[val] === undefined) return false;
95+
var valIndexs = this.map[val].arr;
96+
var delIndex = valIndexs[valIndexs.length - 1];
97+
var lastValue = this.arr.pop();
98+
if (valIndexs.length === 1) {
99+
delete this.map[val];
100+
} else {
101+
valIndexs.pop();
102+
delete this.map[val].map[delIndex];
103+
}
104+
if (lastValue !== val) {
105+
var lastValueIndex = this.map[lastValue].map[this.arr.length];
106+
this.map[lastValue].arr[lastValueIndex] = delIndex;
107+
delete this.map[lastValue].map[this.arr.length];
108+
this.map[lastValue].map[delIndex] = lastValueIndex;
109+
this.arr[delIndex] = lastValue;
110+
}
111+
return true;
112+
};
113+
114+
/**
115+
* @return {number}
116+
*/
117+
RandomizedCollection.prototype.getRandom = function() {
118+
var num = Math.floor(Math.random() * this.arr.length);
119+
return this.arr[num];
120+
};
121+
122+
/**
123+
* Your RandomizedCollection object will be instantiated and called as such:
124+
* var obj = new RandomizedCollection()
125+
* var param_1 = obj.insert(val)
126+
* var param_2 = obj.remove(val)
127+
* var param_3 = obj.getRandom()
128+
*/
129+
```
130+
131+
**Explain:**
132+
133+
nope.
134+
135+
**Complexity:**
136+
137+
* Time complexity : O(1).
138+
* Space complexity : O(n).

0 commit comments

Comments
 (0)