Problem:
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.
Analysis:
This is a typical way to manipulating two pointers of an array.
Solutions:
C++:
int removeElement(int A[], int n, int elem) {
if(n==0) return n;
if(n==1){
if(A[0]==elem) return 0;
else return 1;
}
int end=n-1;
for(int start=n-1; start>=0; --start){
if(A[start]==elem){
if(start==end){
--end;
}else{
int temp=A[end];
A[end]=A[start];
A[start]=temp;
--end;
}
}
}
return end+1;
}
Java:
Python: