Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
auto cnt=count(nums.begin(),nums.end(),0);
if(cnt!=0)
{
vector<int>::iterator it=nums.begin();
while(it!=nums.end())
{
if(*it==0)
it=nums.erase(it);
else
++it;
}
}
nums.insert(nums.end(),cnt,0);
}
};
去年在C++ Primer上看完泛型算法,然后在Leetcode上看到了这道题,就想到了这个解法。
其实有很多更简单的解法,比如下面这个:
class Solution {
public:
void moveZeroes(vector<int> &nums) {
for (int index = 0, current = 0; current < nums.size(); current++) {
if (nums[current] != 0)
swap(nums[index++], nums[current]);
}
}
};