283. Move Zeroes

 

Promble

link: https://leetcode.com/problems/move-zeroes/description

Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Input: nums = [0]
Output: [0]

Approach 1

Thought

  1. def slow:int is one of the two pointers.
  2. loop fast in range(len(nums))
    1. if nums[fast] != 0 and nums[slow] == 0: nums[slow], nums[fast] = nums[fast], nums[slow] # change the fast and slow in-place in nums.
    2. if nums[slow] != 0: slow += 1

Code

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        slow = 0 

        for fast in range(len(nums)):
            if nums[fast] != 0 and nums[slow] == 0:
                nums[slow], nums[fast] = nums[fast], nums[slow]

            if nums[slow] != 0:
                slow += 1