ZhongKuo0228 / study

0 stars 0 forks source link

283. Move Zeroes #68

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago
  1. pt 作為指針來指向當前非零陣列長度
  2. 掃完一輪後,再將 pt 後面的元素填 0
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        pt = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[pt] = nums[i]
                pt += 1
        for i in range(pt, len(nums)):
            nums[i] = 0
fockspaces commented 1 year ago

GPT improve

  1. 遇到非零直接往前丟(做交換)
  2. 不會將非零互相交換,因為確保是從前往後掃
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        pt = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[pt], nums[i] = nums[i], nums[pt]
                pt += 1