题目

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

示例:

  1. 输入: [0,1,0,3,12]
  2. 输出: [1,3,12,0,0]

说明:

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

    方案一

    def moveZeroes(nums: [int]) -> None:
      """
      Do not return anything, modify nums in-place instead.
      """
      head = 0
      for num in nums:
          if num != 0:
              nums[head] = num
              head += 1
      # 剩余部分用0填充
      nums[head:] = (len(nums) - head) * [0]
    

    方案二(双指针)

    class Solution:
      def moveZeroes(self, nums: List[int]) -> None:
          """
          Do not return anything, modify nums in-place instead.
          """
          n = len(nums)
          if n <= 1:
              return
    
          try:
              # i 为第一个值为 0 元素的 index
              i = nums.index(0)
          except ValueError: # 表示数组中没有 0
              return
    
          j = i + 1
          while j < n:
              if nums[j] != 0:
                  nums[i] = nums[j]
                  i += 1
              j += 1
    
          # 填充剩余部分为 0
          while i < n:
              nums[i] = 0
              i += 1
    

原文

https://leetcode-cn.com/explore/featured/card/array-and-string/202/conclusion/796/