Skip to content

Commit e7781b1

Browse files
update 380
1 parent 0482938 commit e7781b1

File tree

1 file changed

+6
-1
lines changed
  • src/main/java/com/fishercoder/solutions/firstthousand

1 file changed

+6
-1
lines changed

Diff for: src/main/java/com/fishercoder/solutions/firstthousand/_380.java

+6-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ public class _380 {
1111
public static class Solution1 {
1212
/**
1313
* credit: https://leetcode.com/problems/insert-delete-getrandom-o1/discuss/85401/Java-solution-using-a-HashMap-and-an-ArrayList-along-with-a-follow-up.-(131-ms)
14+
* 1. use an arraylist and a hashmap;
15+
* 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
1417
*/
1518
public static class RandomizedSet {
1619
Map<Integer, Integer> map;
@@ -28,7 +31,7 @@ public boolean insert(int val) {
2831
return false;
2932
}
3033
map.put(val, list.size());
31-
list.add(list.size(), val);
34+
list.add(val);
3235
return true;
3336
}
3437

@@ -40,6 +43,8 @@ public boolean remove(int val) {
4043
if (removeIndex != list.size() - 1) {
4144
//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)
4245
int lastElement = 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
4348
list.set(removeIndex, lastElement);
4449
map.put(lastElement, removeIndex);
4550
}

0 commit comments

Comments
 (0)