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
- def slow:int is one of the two pointers.
- loop fast in range(len(nums))
- 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.
- 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