|
4 | 4 | import java.util.Map;
|
5 | 5 | import java.util.Random;
|
6 | 6 |
|
7 |
| -/**381. Insert Delete GetRandom O(1) - Duplicates allowed |
8 |
| - * |
9 |
| -Design a data structure that supports all following operations in average O(1) time. |
10 |
| -
|
11 |
| -Note: Duplicate elements are allowed. |
12 |
| -insert(val): Inserts an item val to the collection. |
13 |
| -remove(val): Removes an item val from the collection if present. |
14 |
| -getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains. |
15 |
| -Example: |
16 |
| -
|
17 |
| -// Init an empty collection. |
18 |
| -_381 collection = new _381(); |
19 |
| -
|
20 |
| -// Inserts 1 to the collection. Returns true as the collection did not contain 1. |
21 |
| -collection.insert(1); |
22 |
| -
|
23 |
| -// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1]. |
24 |
| -collection.insert(1); |
25 |
| -
|
26 |
| -// Inserts 2 to the collection, returns true. Collection now contains [1,1,2]. |
27 |
| -collection.insert(2); |
28 |
| -
|
29 |
| -// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3. |
30 |
| -collection.getRandom(); |
31 |
| -
|
32 |
| -// Removes 1 from the collection, returns true. Collection now contains [1,2]. |
33 |
| -collection.remove(1); |
34 |
| -
|
35 |
| -// getRandom should return 1 and 2 both equally likely. |
36 |
| -collection.getRandom();*/ |
37 | 7 | public class _381 {
|
38 | 8 | public static class Solution1 {
|
39 | 9 |
|
@@ -65,7 +35,7 @@ public boolean insert(int val) {
|
65 | 35 | contains = false;
|
66 | 36 | }
|
67 | 37 | forwardMap.put(val,
|
68 |
| - index);//this will overwrite the preivous key with a new index if the key already exists |
| 38 | + index);//this will overwrite the preivous key with a new index if the key already exists |
69 | 39 | reverseMap.put(index, val);
|
70 | 40 | index++;
|
71 | 41 | return contains;
|
|
0 commit comments