【Leetcode】python - [283] Move Zeroes 個人解法筆記

題目出處

283. Move Zeroes

難度

easy

個人範例程式碼 - two pointers

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        start, end = 0, 0
        while(end < len(nums)):
            if(nums[end] != 0): # != 0
                nums[start], nums[end] = nums[end], nums[start] # change
                start +=1
            end += 1

        return nums

算法說明

同向 pointers,因為題目有說要保留「the relative order」(相對順序)

start 保留最後指向 0 位置 (在指到第一個 0 之前,都是指數字與 end 一起前進,讓自己互換)

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

input handling

處理沒有 input 的狀況,return []

Boundary conditions

當 end 先行達到 len(nums),就結束迴圈

Reference