【LeetCode数组】 283 Move Zeros

1. 刷题套路

刷题遵循以下步骤(参考覃超在极客时间在算法训练营中的讲解):

  • 读题,审题,看看有没有思路。尝试从以下几个角度出发进行思考:
    • 暴力解法
    • 尝试优化
  • 没有思路的话,跳转discuss,阅读题解
  • 参照discuss思路,尝试自己写出代码
  • 在白纸上写出代码
  • 跳转discuss,翻阅其他人的解法,提供多种思路。

2. 刷题感悟

计算机程序的运行无非 if else 分支跳转,循环运行。所以算法题的解题思路,无非循环,寻找最小重复问题。

3. LeetCode 283 Move Zeros

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]
题目分析: 把0元素移动到数组的末尾

1. 暴力求解

遍历所有元素,交换0与非0元素,参考冒泡排序。

2. 赋值修改原数组法

遍历所有元素,把非0的先放进去,然后把0补全。

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        j = 0
        for i in xrange(len(nums)):
            if nums[i] != 0:
                nums[j] = nums[i]
                j += 1
        while j < len(nums):
            nums[j] = 0
            j += 1
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        j = 0
        for i in xrange(len(nums)):
            if nums[i] != 0:
                nums[j] = nums[i]
                if i != j:
                    nums[i] = 0
                j += 1
            
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值