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

示例:

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

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

解法一:双指针

用指针i持续扫描出非0元素,指针j指向不含0序列的尾部的后一个元素。指针i扫描过程中不断将非0元素于位置j的元素进行交换。

  1. class Solution(object):
  2. def moveZeroes(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: None Do not return anything, modify nums in-place instead.
  6. """
  7. # 两个指针i和j
  8. i = j = 0
  9. while i < len(nums):
  10. # 当前元素!=0,就把其交换到左边,等于0的交换到右边
  11. if nums[i]:
  12. if i != j:
  13. nums[j], nums[i] = nums[i], nums[j]
  14. j += 1
  15. i += 1