美文网首页
移动零 python

移动零 python

作者: 吕阳 | 来源:发表于2019-03-19 10:25 被阅读0次

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。
  • 执行用时为 36 ms 的范例
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        
        n = len(nums)
        z = 0
        i = 0
        while i + z < n:
            if nums[i] == 0:
                z += 1
                del nums[i]
            else:
                i += 1
        while z > 0:
            nums.append(0)
            z -= 1
  • 执行用时为 40 ms 的范例
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        j = 0
        for i in range(len(nums)):
            if nums[i] !=0:
                nums[j], nums[i] = nums[i], nums[j]
                j +=1

最多提交

  • 执行用时为 44 ms 的范例
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        total = len(nums)
        none_zero = 0

        for i in nums:
            if i == 0:
                continue
            nums[none_zero] = i
            none_zero += 1

        for i in range(none_zero, total, 1):
            nums[i] = 0
  • 48ms
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        i = 0
        j = 0
        while i < length and j < length:
            if  nums[i] != 0:
                i += 1
                j = max(i, j)
            elif nums[j] == 0:
                j += 1
            else:
                nums[i], nums[j] = nums[j], nums[i]
            

相关文章

  • 移动零 python

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 说明: 必...

  • [LeetCode][Python]283. 移动零

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 输入: [...

  • Python LeetCode-283 移动零

    1.题目描述: 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示...

  • LeetCode-python 283.移动零

    题目链接难度:简单 类型: 数组 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾...

  • Python编程题23--移动零

    题目 给定一个非空列表 nums,请将 nums 中所有 0 移动到列表的末尾,同时保持非零元素的相对顺序。 注意...

  • 【移动零】

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 class Sol...

  • 移动零

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 说明: 必...

  • 移动零

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例:输入: [0...

  • 移动零

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 输入: [...

  • 移动零

    题目描述:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例:输...

网友评论

      本文标题:移动零 python

      本文链接:https://www.haomeiwen.com/subject/hlowmqtx.html