We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 3718532 commit 8c56452Copy full SHA for 8c56452
src/main/java/com/fishercoder/solutions/_380.java
@@ -36,12 +36,14 @@ public boolean remove(int val) {
36
if (!map.containsKey(val)) {
37
return false;
38
} else {
39
- int lastElement = list.get(list.size() - 1);
40
- int index = map.get(val);
41
- list.set(index, lastElement);
42
- map.put(lastElement, index);
43
- list.remove(list.size() - 1);
+ int removeIndex = map.get(val);
+ if (removeIndex != list.size() - 1) {//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)
+ int lastElement = list.get(list.size() - 1);
+ list.set(removeIndex, lastElement);
+ map.put(lastElement, removeIndex);
44
+ }
45
map.remove(val);
46
+ list.remove(list.size() - 1);
47
return true;
48
}
49
0 commit comments