Skip to content

Commit 8c56452

Browse files
fix 380
1 parent 3718532 commit 8c56452

File tree

1 file changed

+7
-5
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+7
-5
lines changed

src/main/java/com/fishercoder/solutions/_380.java

+7-5
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,14 @@ public boolean remove(int val) {
3636
if (!map.containsKey(val)) {
3737
return false;
3838
} 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);
39+
int removeIndex = map.get(val);
40+
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)
41+
int lastElement = list.get(list.size() - 1);
42+
list.set(removeIndex, lastElement);
43+
map.put(lastElement, removeIndex);
44+
}
4445
map.remove(val);
46+
list.remove(list.size() - 1);
4547
return true;
4648
}
4749
}

0 commit comments

Comments
 (0)