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.
这道题是的时间复杂度是O(N), 想法很直接。双指针,一个指针用来循环,另一个指针就是指向需要换位的地方。即刚开始没有遇到零的时候,就是和循环指针相同,一旦遇到零了以后,这个指针就是记录着最开始的零的位置,遇到非零的循环值和它交换就行了。这样做也保证了操作次数的最少。
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if not nums: return None
zero = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[zero] = nums[zero], nums[i]
zero += 1