#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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.
分析:从后向前,每次找到0,然后就将其后面部分每个元素都前移一位,将该0放到最后位置。
这样带来的问题是最前面的0被移动到最后,也可以,也就是所有0的位置是逆置的,然后最后把
0的部分逆置一下即可。输出0的总个数num,则从n-1~n-num处的0逆置一下
如果从前向后,每次找到0,就把该0移动到最后,这样是可以的,
时间复杂度:O(n^2)
输入:
5
0 1 0 3 12
1
1
1
0
2
0 0
输出:
1 3 12 0 0
1
0
0 0
关键:
1 从后向前,每次找到0,然后就将其后面部分每个元素都前移一位,将该0放到最后位置。
这样带来的问题是最前面的0被移动到最后,也可以,也就是所有0的位置是逆置的,然后最后把
0的部分逆置一下即可。输出0的总个数num,则从n-1~n-num处的0逆置一下
*/
class Solution {
public:
void moveZeroes(vector<int>& nums) {
//从后向前,每次找到0,就将后面部分前移一位
if(nums.empty())
{
return;
}
int count = 0;
int size = nums.size();
for(int i = size - 1 ; i >= 0 ; i--)
{
if(0 == nums.at(i))
{
count++;
//开始移动位置: i+1~size-1都向前移动
for(int j = i + 1 ; j <= size - 1 ; j++)
{
nums.at(j-1) = nums.at(j);
}
//将0放在最后
nums.at(size - 1) = 0;
}
}
//接下来就是逆置最后的0,
reverse(nums.begin() + size - count , nums.end());
}
};
void print(vector<int>& result)
{
if(result.empty())
{
cout << "no result" << endl;
return;
}
int size = result.size();
for(int i = 0 ; i < size ; i++)
{
cout << result.at(i) << " " ;
}
cout << endl;
}
void process()
{
vector<int> nums;
int value;
int num;
Solution solution;
vector<int> result;
while(cin >> num )
{
nums.clear();
for(int i = 0 ; i < num ; i++)
{
cin >> value;
nums.push_back(value);
}
solution.moveZeroes(nums);
print(nums);
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}