283. Move Zeroes



238. Move Zeroes (Easy) 移动零

题干

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.

Example 1:

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

Example 2:

Input: nums = [0] Output: [0]

Constraints:

Follow up: Could you minimize the total number of operations done?

解题思路

我的思路

快慢指针,慢指针遇零则停,非零自增;快指针每次自增;当快慢指针一个是0,一个非0时,交换值

答案

我的答案

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        zero_idx = 0
        for i in range(len(nums)):
            if nums[zero_idx] == 0 and nums[i] != 0:
                nums[zero_idx], nums[i] = nums[i], nums[zero_idx]

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