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:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
要求不开额外数组内存,可以开两个变量,一个是统计0个个数,一个是当前数组不为0的位置到哪里了,每次不为零的数就往这个index移动,最后用统计出的0个个数往数组的最后补
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ zero_count = 0 index = 0 for i in range(len(nums)): if nums[i] == 0: zero_count += 1 else: nums[index] = nums[i] index += 1 for i in range(index, index + zero_count, 1): nums[i] = 0