题目: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.
例子:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
要求:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
思考:
1、遍历数组,设置一个0元素的标志位flag,记录0元素的位置
2、当第一个数组元素=0时,flag记录下它的位置,后一个元素等于=0,则继续遍历;不等于0,
则交换,此时flag++,