leetcode 283. 移动零

题目:

思路

分情况:

  1. 如果列表只有一个值或者值都是重复,则返回列表即可
  2. 获取当前列表0的个数,从末尾开始遍历:如果0的个数=列表0个数,说明0都在列表后面且连续至0末尾,此时不需要进行0的转移。0的个数!=列表0个数,找到末尾遍历时最后遍历为0的数的位置i,这时候只需要遍历前i-1个数,找出0移至列表末尾即可

ps:

遍历前n项,如果更严谨点,需要分情况来定义i的值。

一种是 末尾第一个数不为0 此时i =len(nums),即遍历应该为列表长度 如[3,5,6]

另一种:末尾第一个数为0 此时i = len(nums)-1, 如 [1,0,3,0] 遍历前n项可以为[0:3]

而不用判断来定义i也可以是因为移动0是把0移至原列表的末尾,如:

i = len(nums)-1

假如 nums = [1,0,2,6] 此时遍历[1,0,2]也不会影响 因为是把0移至原列表的末尾

nums=[1,0,2,6,0] 此时遍历[1,0,2,6]

while nums[i]==0 and i>0,其中一种情况 [1,0,0]

python 复制代码
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        count = nums.count(0)
        length = len(nums)
        if count ==len(nums) or len(nums)==1:
            return nums
        i = len(nums)-1
        t = 0
        while nums[i]==0 and i>0:
            t+=1
            if nums[i-1]!= 0:
                #0都排在列表后边且连续排至末位
                if t== count:
                    return nums
                else:
                    count = count - t
                    break
            else:
                i-=1
        j = 0
        while j<i and count>0:
            if nums[j]==0:
                nums.append(nums.pop(j))
                count-=1
            else:
                j+=1

严谨点方法:

python 复制代码
class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        count = nums.count(0)
        length = len(nums)
        if count == len(nums) or len(nums)==1:
            return nums
        if nums[-1]== 0:
            i = len(nums)-1
            t = 0
            while nums[i]==0 and i>0:
                t+=1
                if nums[i-1]!= 0:
                #0都排在列表后边且连续排至末位
                    if t== count:
                        return nums
                    else:
                        count = count - t
                        break
                else:
                    i-=1
        else:
            i = len(nums)
        
        j = 0
        while j<i and count>0:
            if nums[j]==0:
                nums.append(nums.pop(j))
                count-=1
            else:
                j+=1
        return nums
相关推荐
S01d13r2 分钟前
gunicorn + flask 处理高并发请求
python·flask·gunicorn
杜子不疼.6 分钟前
《Python列表和元组:从入门到花式操作指南》
开发语言·python
pan0c2312 分钟前
数据处理与统计分析 —— numpy入门
python·numpy
max50060028 分钟前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
秋氘渔1 小时前
综合案例:Python 函数知识整合 — 学生成绩管理系统
开发语言·python
AI 嗯啦2 小时前
SQL详细语法教程(三)mysql的函数知识
android·开发语言·数据库·python·sql·mysql
databook2 小时前
把数学对象画出来:Manim Mobject类库速查手册
python·数学·动效
快去睡觉~3 小时前
力扣400:第N位数字
数据结构·算法·leetcode
图灵学术计算机论文辅导3 小时前
傅里叶变换+attention机制,深耕深度学习领域
人工智能·python·深度学习·计算机网络·考研·机器学习·计算机视觉
ruleslol3 小时前
python30-正则表达式
python·正则表达式