【leetcode】Remove Element

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.

 


题解:用一个len变量记录当前数组的长度。每次遇到元素elem,就把len-1指着的元素换到elem元素所在的地方,然后把len--。要注意的地方就是elem在数组结尾的时候,len减一减到和i相等的时候,就不能再减了,应该结束遍历,返回len的值。

代码如下:

 1 class Solution {
 2 public:
 3     int removeElement(int A[], int n, int elem) {
 4         int len = n;
 5         for(int i = 0;i < len;i ++){
 6             if(A[i] == elem){
 7                 while(A[len - 1] == elem && len > i)
 8                     len--;
 9                 A[i] = A[len-1];
10                 if(len > i)
11                     len --;
12             }
13         }
14         /*for(int i= 0;i < len;i++)
15             cout <<A[i]<<endl;*/
16         return len;
17     }
18 };

 还有一种正序的想法,就是设置一个puthere指针,每次发现和elem不想等的元素,就放到puthere所指向的位置;

java代码如下:

 1 public class Solution {
 2     public int removeElement(int[] A, int elem) {
 3         int puthere = 0;
 4         int n = A.length;
 5         for(int i = 0;i < A.length;i++){
 6             if(A[i] != elem){
 7                 A[puthere] = A[i];
 8                 puthere++;
 9             }
10             else {
11                 n--;
12             }
13         }
14         return n;
15     }
16 }

 

posted @ 2014-06-09 20:30  SunshineAtNoon  阅读(184)  评论(0编辑  收藏  举报