LeetCode:283. 移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

 1 class Solution:
 2     def moveZeroes(self, nums: List[int]) -> None:
 3         """
 4         Do not return anything, modify nums in-place instead.
 5         """
 6         pos = 0
 7         for i in range(len(nums)):
 8             if nums[i]:     #如果不为 0 则往前移动
 9                 nums[pos] = nums[i]
10                 pos+=1
11         
12         for i in range(pos,len(nums)):  #将后面的内容用 0 代替
13             nums[i] = 0
14 
15         

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/Halo-zyh-Go/p/12411833.html