思路:
双指针(快慢指针)。
代码一:
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 j = 0 8 for i in range(len(nums)): 9 if nums[i] != 0: 10 nums[j] = nums[i] 11 j += 1 12 while j < len(nums): 13 nums[j] = 0 14 j += 1
代码二:
1 class Solution(object): 2 def moveZeroes2(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: None Do not return anything, modify nums in-place instead. 6 """ 7 j = 0 8 for i in range(len(nums)): 9 if nums[i] != 0: 10 nums[i], nums[j] = nums[j], nums[i] 11 j += 1