File tree Expand file tree Collapse file tree 1 file changed +7
-5
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +7
-5
lines changed Original file line number Diff line number Diff 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 }
You can’t perform that action at this time.
0 commit comments