[leetcode: Python]283. Move Zeroes

来源:互联网 发布:linux新建用户并授权 编辑:程序博客网 时间:2024/06/11 19:30

题目:
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].

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

题意:
把给定数组中的0移动到最后。
注意原地移动,不能复制数组。最小化操作步数。

方法一:性能185ms

class Solution(object):    def moveZeroes(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        c = nums.count(0)        while c:            del nums[nums.index(0)]            nums.append(0)            c -= 1

方法二:性能66ms

class Solution(object):    def moveZeroes(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        zeros = 0        safe = 0        for n in nums:            if n != 0:                nums[safe] = n                safe += 1            else:                zeros += 1        for i in range(zeros):            nums[safe] = 0            safe += 1
0 0
原创粉丝点击