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) {
36
36
if (!map .containsKey (val )) {
37
37
return false ;
38
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 );
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
+ }
44
45
map .remove (val );
46
+ list .remove (list .size () - 1 );
45
47
return true ;
46
48
}
47
49
}
You can’t perform that action at this time.
0 commit comments