今天的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的情况了。