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:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations.
第一想法是类比冒泡排序写个算法,但是又觉得太繁琐。后来想想,简单点,遇到零就删除,然后再数组末尾添加上就好了,只是对细节上需要做一些处理。具体代码如下。
void moveZeroes(vector<int>& nums) { int size = nums.size(); int counter = 0; int i = 0; while(i+counter<size){ if (nums[i] == 0) { nums.erase(begin(nums) + i); nums.push_back(0); counter++; i = 0;//这一步很重要,需要理解。 } else i++; } }