Remove Element
Loop invariant
Setup a wall, on the left side of the wall are the elements which do not contain the target
.
When a new element comes and it does not equal to the target
, enlarge the space on the left side of the wall, and move the new element into the left side of the wall.
Source code Read on Github
1 public class Solution {
2 public int removeElement(int[] A, int elem) {
3 // IMPORTANT: Please reset any member data you declared, as
4 // the same Solution instance will be reused for each test case.
5 if(A.length == 0) return 0;
6
7 int len = 0;
8
9 for(int i = 0; i< A.length; i++){
10 if(A[i] != elem) A[len++] = A[i];
11 }
12
13
14 return len;
15 }
16 }