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.
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i=0, j=n-1;
while( i<=j) {
if( A[i] == elem) {
while( j>=i && A[j] == elem ) j--;
if( j<= i ) break;
A[i] = A[j--];
}
i++;
}
return i;
}
};
public class Solution {
public int removeElement(int[] A, int elem) {
//113251631345465, 1
//check input.
if(A==null || A.length<1) return 0;
int i=-1;
for(int j=0; j<A.length; j++) {
if(A[j]!=elem) {
A[++i] = A[j];
}
}
return i+1;
}
}
//this approach can keep the original order.
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int i=-1, j=0;
while(j<n) {
if(A[j]!=elem) {
A[++i] = A[j++];
} else {
++j;
}
}
return i+1;
}
};