leetcode 283. Move Zeroes( Python )

862 阅读21分钟

描述

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 都放到后到,主要在通过索引交换元素。时间复杂度为 O(N),空间复杂度为 O(1)。

解答

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        zero_i = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[i], nums[zero_i] = nums[zero_i], nums[i]
                zero_i += 1
        return nums                

运行结果

Runtime: 28 ms, faster than 97.65% of Python online submissions for Move Zeroes.
Memory Usage: 12.9 MB, less than 5.49% of Python online submissions for Move Zeroes.

每日格言:过去属于死神,未来属于你自己。

感谢支持 支付宝

支付宝

微信

微信