題目:
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.
題解:
這道題跟remove duplicate sorted array是一樣的。。。還是雙指標,一個幫忙記錄length外加替換不是elem的值,一個幫忙往前找。
程式碼如下:
1 public int removeElement(int[] A, int elem) {
2 if(A==null||A.length == 0)
3 return 0;
4
5 int len = 0;
6 for(int i =0; i < A.length;i++){
7 if(A[i] != elem){
8 if(A[len]!=A[i])
9 A[len]=A[i];
10 len++;
11 }
12 }
13 return len;
14 }
2 if(A==null||A.length == 0)
3 return 0;
4
5 int len = 0;
6 for(int i =0; i < A.length;i++){
7 if(A[i] != elem){
8 if(A[len]!=A[i])
9 A[len]=A[i];
10 len++;
11 }
12 }
13 return len;
14 }