[LeetCode] Remove Element

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.

解题思路:

题意中说可以更改数组顺序,只需要目标元素移到数组后面即可。需要注意的就是若从后面掉过来的元素仍等于elem,前面的指针无需递增。

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        if(n==0){
            return n;
        }
        int newN=n;
        for(int i=0; i<newN; i++){
            if(A[i]==elem){
                int temp=A[newN-1];
                A[newN-1]=A[i];
                A[i]=temp;
                newN--;
                if(A[i]==elem){
                    i--;
                }
            }
        }
        return newN;
    }
};

二次刷题(update in 2015-07-31)

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int newLen = nums.size();
        for(int i = 0; i<newLen; i++){
            if(nums[i]==val){
                int temp = nums[i];
                nums[i] = nums[newLen-1];
                nums[newLen - 1] = temp;
                i--;
                newLen--;
            }
        }
        return newLen;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注