【问题标题】:How to maintaining relative order of non-zero elements during array sorting?如何在数组排序期间保持非零元素的相对顺序?
【发布时间】:2020-10-08 18:53:59
【问题描述】:

给定一个数组 nums,我正在编写一个函数来将所有 0 移动到它的末尾,同时保持非零元素的相对顺序:

class Solution {
public:
    void moveZeroes(vector<int>& nums) 
    {
        const std::vector<int> v;
        int count = 0;
        int i;
        int n = nums.size();
        for(i=0;i<n;i++)
        {
            if(nums[i]!=0)
            { v.push_back[count++]=nums[i];
            }
        }
        while(count<n)
        {
            v.push_back[count++]=0;
        }
        
    }
};

但我无法弄清楚以下错误:

Line 12: Char 17: error: reference to non-static member function must be called
        { v.push_back[count++]=nums[i];
          ~~^~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1184:7: note: possible target for call
  push_back(const value_type& __x)
  ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1200:7: note: possible target for call
  push_back(value_type&& __x)
  ^

【问题讨论】:

  • 不允许修改v,因为它被声明为const
  • push_back 是一个函数。不太确定您要做什么。也许v.push_back(nums[i]);?一旦你删除了 const 就是。
  • 这是使用std::stable_partition的单行解决方案
  • 我确定你必须“就地”完成,无需其他向量的帮助

标签: c++ arrays vector


【解决方案1】:
  • 您不能修改声明为const 的对象。
  • push_back 是一个函数,你的用法是错误的。

该过程可以通过使用std::remove 删除0s 和std::fill0s 放在向量后面的空间中,并删除0s。

#include <algorithm>

class Solution {
public:
    void moveZeroes(vector<int>& nums) 
    {
        vector<int>::iterator pos = std::remove(nums.begin(), nums.end(), 0);
        std::fill(pos, nums.end(), 0);
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    相关资源
    最近更新 更多