-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path381.insert-delete-get-random-o-1-duplicates-allowed.java
More file actions
63 lines (53 loc) · 1.8 KB
/
381.insert-delete-get-random-o-1-duplicates-allowed.java
File metadata and controls
63 lines (53 loc) · 1.8 KB
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
/*
* @lc app=leetcode id=381 lang=java
*
* [381] Insert Delete GetRandom O(1) - Duplicates allowed
*/
// @lc code=start
class RandomizedCollection {
Map<Integer, Set<Integer>> map;
List<Integer> list;
Random rand = new Random();
/** Initialize your data structure here. */
public RandomizedCollection() {
map = new HashMap<>();
list = new ArrayList<>();
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
if (!map.containsKey(val)) {
map.put(val, new HashSet<Integer>());
}
map.get(val).add(list.size());
list.add(val);
return map.get(val).size() == 1;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if (!map.containsKey(val) || map.get(val).size() == 0) {
return false;
}
int lastElement = list.get(list.size() - 1);
int index = map.get(val).iterator().next();
map.get(val).remove(index);
// replace and add
list.set(index, lastElement);
map.get(lastElement).add(index);
//delete
map.get(lastElement).remove(list.size() - 1);
list.remove(list.size() - 1);
return true;
}
/** Get a random element from the collection. */
public int getRandom() {
return list.get(rand.nextInt(list.size()));
}
}
/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
// @lc code=end