直接解
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 num = 0 8 while 0 in nums: 9 num = num + 1 10 nums.remove(0) 11 while num > 0: 12 num = num - 1 13 nums.append(0) 14 return nums 15
官方双指针解法,时间复杂度低,O(n)
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 left = right = 0 8 n = len(nums) 9 while right < n: 10 if nums[right] != 0: 11 nums[left], nums[right] = nums[right], nums[left] 12 left += 1 13 right += 1 14 return nums 15