【Remove Elements】cpp

题目

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.

代码

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

Tips:

设定一个指针,始终指向要插入的元素的为止。

或者更简洁一些,用STL函数直接一行代码搞定:

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        std::distance(A,remove(A,A+n,elem));
    }
};

 ==================================

第二次过这道题,试了几次才AC,代码如下:

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

设立一个尾部的指针,保持尾部指针指向的元素不是val。

从前向后遍历,发现val就与last所指代的元素交换,最后返回last+1即可。

这么做虽然可以AC,而且效率还可以,但是确实麻烦了。原因是受到解题思维的影响,反而忽视最直接的办法了。

原文地址:https://www.cnblogs.com/xbf9xbf/p/4450451.html