leetcode-283. Move Zeroes 在list里删除某个元素,并插入某个元素

来源:互联网 发布:淘宝网商贷利息 编辑:程序博客网 时间:2024/06/06 01:11

题目:

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

题意:

给定一个数组,将非0元素按原来顺序排列,并将所有0元素插在数组后面。


代码:

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        
        n = nums.count(0)
        
        while (0 in nums) :
            nums.remove(0)
        
        for i in range(n):
            nums.append(0)
        


笔记:

思路:先将nums中0的个数统计出来,然后将nums中的0删除,除了0以外,其他元素都按原来顺序排列,最后在末尾插入统计出来的0的个数

nums.count(0):统计nums中0的个数

remove函数:测试了下,remove函数一次只能删除nums中的一个0,因此此处用了循环的方法来删除0

append:最后,在nums末尾插入被删除的0


0 0