1 移动零
/*
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.
Notice
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
Example
Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
*/
// Example program
#include <iostream>
#include <vector>
void ZerosMoves(std::vector<int>& nums) {
std::vector<int>::iterator it1, it2;
it1 = it2 = nums.begin();
while (it1 != nums.end()) {
if (*it1 == 0) {
it1++;
} else if (it1 != it2) {
std::swap(*(it1++), *(it2++));
} else {
it1++;
it2++;
}
}
}
int main()
{
int array[5] = {0,1,0,3,12};
std::vector<int> nums(array, array + 5);
ZerosMoves(nums);
for(int val:nums) {
std::cout << " " << val;
}
}