Remove Element leetcode java

题目:

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     }

posted @ 2014-07-27 09:58  爱做饭的小莹子  阅读(2210)  评论(0编辑  收藏  举报