• 【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,而且效率还可以,但是确实麻烦了。原因是受到解题思维的影响,反而忽视最直接的办法了。

  • 相关阅读:
    POJ 2987:Firing(最大权闭合图)
    BZOJ 1001:[BeiJing2006]狼抓兔子(最小割)
    HDU 1007:Quoit Design(分治求最近点对)
    POJ 1986:Distance Queries(倍增求LCA)
    HDU 3879 && BZOJ 1497:Base Station && 最大获利 (最大权闭合图)
    BZOJ-1011 遥远的行星
    BZOJ-1044 木棍分割
    BZOJ-1042 硬币购物
    BZOJ-1050 旅行
    BZOJ-1037 生日聚会
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4450451.html
Copyright © 2020-2023  润新知