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.
public class Solution {
public int removeElement(int[] A, int elem) {
// Start typing your Java solution below
// DO NOT write main() function
if(A.length<1)
return A.length;
int i=0, j=A.length-1;
while(i<j){
if(A[i]==elem){
while(A[j]==elem && i<j)
j--;
if(i==j)
break;
A[i] = A[j];
j--;
}
i++;
}
if(A[j]==elem)
j--;
return j+1;
}
}
------------------------------------------------------------------------------------------------------------------------------------------
LL's solution:
public class Solution {
public int removeElement(int[] A, int elem) {
// Start typing your Java solution below
// DO NOT write main() function
if(A.length<1)
return 0;
int curValue;
int curIndex = 0;
for(int i = 0; i<A.length; i++){
curValue = A[curIndex];
if(curValue==elem){
if(A[i]!=elem){
A[curIndex] = A[i];
A[i] = elem;
curIndex++;
}
}
else{
curIndex++;
}
}
return curIndex;
}
}