【LeetCode 热题 100】283. 移动零 | python【简单】0

坚持就是胜利!

题目:

283. 移动零

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

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

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

注意点:

  1. 将数组前移后,每个数字的索引会变
  2. 进阶:尽量减少完成的操作次数

标准做法:

双指针想法:使左右指针从头开始,右指针不断右移,左指针在右指针遇到非零的数时,与右指针的数交换后才右移

保证:非零-左指针-零-右指针-未识别

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        n = len(nums)
        left = right = 0
        while right < n:
            if nums[right] != 0:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1
            right += 1

作者:力扣官方题解
链接:https://leetcode.cn/problems/move-zeroes/solutions/489622/yi-dong-ling-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 时间复杂度:O(n),其中 n 为序列长度。每个位置至多被遍历两次。

  • 空间复杂度:O(1)。只需要常数的空间存放若干变量。

自己的做法:【通过但有点擦边】

先把不为0的数存在其他数组,再加满0【这个算是存了数组了吗】时间复杂度为O(N)

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

1.复杂度高n2

10分钟写一个遇到0直接把所有数往前移动的代码

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

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值