Leetcode 283. Move Zeroes

Problem

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.

Algorithm

Simulate, when 0 found, to exchange it with the fist following non-zero value.

Code

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        num_len = len(nums)
        index1, index2 = 0, 0
        while index2 < num_len:
            while index1 < num_len and nums[index1]:
                index1 += 1
            index2 = index1 + 1
            while index2 < num_len and not nums[index2]:
                index2 += 1
            
            if index2 < num_len:
                buffer = nums[index1]
                nums[index1] = nums[index2]
                nums[index2] = buffer

你可能感兴趣的:(Leetcode,解题报告,入门题,leetcode,解题报告)