LeetCode: Remove Element [026]

时间:2014-05-18 14:53:56   收藏:0   阅读:208

【题目】

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 Duplicates from Sorted Array


【代码】

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        if(n==0)return 0;
        int newArrayTail=-1;    //与去重不同,本题中第一个值就可能会被删除
        int pointer=0;
        while(pointer<n){
            if(A[pointer]==elem)pointer++;
            else {A[++newArrayTail]=A[pointer];pointer++;}
        }
        return newArrayTail+1;
    }
};


LeetCode: Remove Element [026],布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!