lc283. Move Zeroes

155 阅读1分钟

283. Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note:

You must do this in-place without making a copy of the array. Minimize the total number of operations.

思路:遍历,判断是否为0,不为0,就插到标示位n=0,标示位n++

代码:python3

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