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.
LeetCode:链接
这题和 LeetCode75:Sort Colors有点像,但是75题不要求顺序。
本题调整的是非0数字以此保证顺序不变,将满足的放到前面,不满足的直接交换到后面。本题就是采用了交换的方式,首先找到第一个0记录位置i,再找到第一个非0记录位置j,将i与j交换,交换后i向后移动一个位置,j继续向后查找非0元素,重复交换的过程直至j走到数组的最后。
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
start = 0
for idx in range(len(nums)):
if nums[idx] != 0:
nums[start], nums[idx] = nums[idx], nums[start]
start += 1