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.
Example:
Input:[0,1,0,3,12]
Output:[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.
思路:
1.从头遍历,判断此时是不是0,是则跟后面不是0的调换
#pragma once
#include <iostream>
#include<vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int end;
for (int first = 0; first < nums.size()-1; first++)
{
//如果是0,则跟后面不是0的调换
if (nums[first] == 0)
{
end = first;
while (nums[end] == 0)
{
end++;
if (end >= nums.size())
{
return;
}
}
if (end < nums.size())
{
int temp = nums[first];
nums[first] = nums[end];
nums[end] = temp;
}
}
}
}
};