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 numsi==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
相关推荐
TechWayfarer6 分钟前
IP精准定位服务在快递网点规划中的应用:如何用客户位置数据辅助选址
大数据·网络·python·tcp/ip·交通物流
elseif12311 分钟前
【C++】vector 详细版
开发语言·c++·算法
CSND74020 分钟前
零基础学Python合集---3:字符串的定义和常用方法
人工智能·python
变量未定义~24 分钟前
既约分数、阶乘约数、逆元、最大质因子个数【算法赛】
算法
五月君_36 分钟前
放弃 Python,Kimi 用 TS + Node.js 重写了一个 Kimi Code
开发语言·python·node.js
还是鼠鼠37 分钟前
AI掘金头条新闻系统 (Toutiao News)-获取用户信息
后端·python·mysql·fastapi·web
Cloud_Shy6181 小时前
解读《Effective Python 3rd Edition》:从练气到老魔
开发语言·python
SunnyDays10111 小时前
Python 操作 Excel 超链接:添加网页、文件、工作表和图片链接
python·excel
KaMeidebaby1 小时前
卡梅德生物技术快报|Western Blot 实验应用:肺肠轴机制研究全流程技术解析
前端·数据库·人工智能·算法·百度
li星野1 小时前
RAG优化系列:HyDE(假设文档嵌入)——让LLM先写答案再检索
python·学习