LeetCode 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.

题目分析及思路

给定一个数组,要求将这个数组中所有的0移到数组末尾并保持非零元素相对位置不变。可以先得到零元素的个数,然后循环将零进行移除和在末尾添加。

python代码 

class Solution:

    def moveZeroes(self, nums: List[int]) -> None:

        """

        Do not return anything, modify nums in-place instead.

        """

        zeros = nums.count(0)

        for _ in range(zeros):

            nums.remove(0)

            nums.append(0)

        

        

 

posted on 2019-03-25 10:00  锋上磬音  阅读(85)  评论(0编辑  收藏  举报