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

  • 相关阅读:
    QML vs WEB
    《TO C产品经理进阶》
    《TO B产品设计标准化》
    《多元思维模型》跨学科及其核心思维模型
    产品经理审美训练
    Aria2多线程轻量级批量下载利器
    正则表达式
    如何开发一个用户脚本系列教程
    Aria2自动下载
    助贷
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4450451.html
Copyright © 2011-2022 走看看