栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

关于这两天刷LeetCode因为python基础不扎实而吃的大亏(二)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于这两天刷LeetCode因为python基础不扎实而吃的大亏(二)

今天的735行星冲撞难度并不大,我利用栈的结构很快有了思路并根据书写的伪代码在LC编译器上完成了代码,但奇怪的是在跑[1,-2,-2,-2]用例时怎样都通不过

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        top,n = -1,len(asteroids)
        stack = []

        for i in range(n):
            if top == -1 or stack[top] < 0 or asteroids[i] > 0:
                stack.append(asteroids[i])
                top += 1
                continue

            while stack[top] > 0 and top >= 0 and abs(stack[top]) < abs(asteroids[i]):
                stack.pop(top)
                top -= 1

            if top < 0 or stack[top] < 0:
                stack.append(asteroids[i])
                top += 1
            
            elif stack[top] > 0 and abs(stack[top]) == abs(asteroids[i]):
                stack.pop(top)
                top -= 1
        
        return stack
            

原因就在于python在编译and判断语句时,如x1 and x2 and x3,如果x1为False那么x2和x3也不用判断了。

问题就出在这里:

while stack[top] > 0 and top >= 0 and abs(stack[top]) < abs(asteroids[i]):

栈pop完1之后,top等于-1,下一次while循环先判断stack[top] > 0,自然就index out of

range了。

但是反过来这样写:

while top >= 0 and stack[top] > 0 and abs(stack[top]) < abs(asteroids[i]):

会先判断top是否大于等于0,就不会出现index out of range的情况了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1011811.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号