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.
Array a deletes all elements whose values are ELEM, and ensures that the first length element of A does not have ELEM. The length is returned.
Idea: Use a double pointer, an element that looks for ELEM from the beginning to the end, an element that looks for non-ELEM from the back to the end, and then exchanges the two. The error points are some boundary conditions.
1 class Solution { 2 public: 3 int removeElement(int A[], int n, int elem) { 4 int i=0,j=n-1; 5 int length=n; 6 while(i<n) 7 { 8 while(j>=0&&A[j]==elem) 9 {10 length--;11 j--;12 }13 14 if (A[i]==elem&&j>i)15 {16 A[i]=A[j];17 i++;18 j--;19 length--;20 }21 else22 {23 i++;24 }25 }26 return length;27 }28 };