Description:
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.
note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
Example:
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Hint:
Link:
https://leetcode.com/problems/move-zeroes/
Analysis:
1.首先注意要求,必须在原数组内完成任务,不能通过复制来完成。
2.刚开始面对这个问题,首先想的是怎么把0 都一个个挪到数组尾部,随便找了几个数尝试了一下,当多个0 出现时你会发现这是件很麻烦的事儿。
3.然后想到可能把非0 的数挪到前边,然后在末尾全补为0。尝试了一下,发现这样果然非常方便。
Source Code(C++):
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j=0;
for (int i=0; i<nums.size(); i++) {
if (nums.at(i)!=0) {
nums.at(j++)=nums.at(i);
}
}
for(int i=j; i<nums.size(); i++) {
nums.at(i)=0;
}
}
};
int main() {
Solution s;
vector<int> nums;
nums.push_back(0);
nums.push_back(1);
nums.push_back(0);
nums.push_back(3);
nums.push_back(12);
s.moveZeroes(nums);
for (int i=0; i<nums.size(); i++) {
cout << nums.at(i) << endl;
}
return 0;
}