Skip to content

283. Move Zeroes #8

@w4irdo

Description

@w4irdo
# 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.

# Python 1

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

# Python 2

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        type nums: List[int]
        Do not return anything, modify nums in-place instead.
        """
        j = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1
  • nums[:] 属于浅拷贝。列表内的元素内存地址并未发生改变。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions