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.
Solution:
1 public class Solution { 2 public int removeElement(int[] A, int elem) { 3 int head = 0; 4 int end = A.length-1; 5 6 while (head<end){ 7 while (head<A.length && A[head]!=elem) head++; 8 if (head>=end) break; 9 while (end>=0 && A[end]==elem) end--; 10 if (head>=end) break; 11 int temp = A[head]; 12 A[head] = A[end]; 13 A[end] = temp; 14 } 15 16 int len = A.length; 17 for (int i=0;i<A.length;i++) 18 if (A[i]==elem){ 19 len = i; 20 break; 21 } 22 23 return len; 24 } 25 }