You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* 2. you always insert at the end of the arraylist and put the index/position of this new item into the map;
16
+
* 3. for deletion, always delete the last item in the arraylist so it's O(1) time, if the last item in the arraylist is not the item we want to delete, we swap it first before we delete
14
17
*/
15
18
publicstaticclassRandomizedSet {
16
19
Map<Integer, Integer> map;
@@ -28,7 +31,7 @@ public boolean insert(int val) {
28
31
returnfalse;
29
32
}
30
33
map.put(val, list.size());
31
-
list.add(list.size(), val);
34
+
list.add(val);
32
35
returntrue;
33
36
}
34
37
@@ -40,6 +43,8 @@ public boolean remove(int val) {
40
43
if (removeIndex != list.size() - 1) {
41
44
//if it's not the last element, then we need to swap it with the last element so that this operation is also O(1)
42
45
intlastElement = list.get(list.size() - 1);
46
+
// using set() API is another key here which gives us O(1),
47
+
// using add() is not only wrong, i.e. it adds an element at this position and shifts all elements on the right of this element to the right, so leading to O(n) time
0 commit comments