Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
The idea is to look for elem
from the left, and swap into its place something from the right of the array, so that all elems
are at the end of the arraypublic int removeElement(int[] A, int elem) {
int oldLength = A.length;
int removed = 0;
int lastValidIndex = A.length-1;
int i = 0;
while(i <= lastValidIndex){
if(A[i] == elem){
A[i] = A[lastValidIndex];
lastValidIndex--;
removed++;
}
else{
i++;
}
}
return oldLength - removed;
}
Read full article from Rafal's Blog - LeetCode 26 – Remove Element
No comments:
Post a Comment