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

Lines changed: 7 additions & 5 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy