leetcode283 移动零

这道题一上来的思路是类似冒泡排序,遇到0就沉下去,但这样的操作次数接近于n^2。

因此,我第二个思路是首先遍历一遍数组,记录下0元素的个数和非0元素的个数,然后在第二次遍历中,用i来表示当前遍历到第几个元素,用temp_i来当前非零元素可以放的位置,当非零元素放完之后,剩余的补0,所以一共需要移动元素n次。

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        zero_count=0
        nonzero_count=0
        for num in nums:
            if num==0:
                zero_count+=1
            else:
                nonzero_count+=1
        temp_i=0
        i=0
        while temp_i<nonzero_count:
            if nums[i]==0:
                i+=1
                continue
            else:
                nums[temp_i]=nums[i]
                temp_i+=1
                i+=1
        while temp_i<len(nums):
            nums[temp_i]=0
            temp_i+=1
        return

但是,只超过了72%的提交。从评论中,我发现了一种更快的方法,一共移动元素的次数是非零元素的个数。代码中,x代表当前非0元素能放的位置。

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值