Description
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.
Solution
代码不长,需要先找到第一个0值,然后依次遍历填补空缺,最后需要把剩下的复制为0
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = 0
while i<len(nums):
if nums[i] ==0:
break
i+=1
start = i # first zero
if start == len(nums):
return nums
for i in range(start,len(nums)):
if nums[i] !=0:
nums[start] = nums[i]
start +=1
else:
continue
for j in range(start,len(nums)):
nums[j]=0
网友评论