給出一列數(shù),負(fù)數(shù)代表向左移動(dòng),正數(shù)代表向右移動(dòng),如果連著的兩個(gè)數(shù)分別向右和向左,則會(huì)碰撞,只剩下絕對值更大的那一個(gè)數(shù),問所有碰撞結(jié)束之后剩下的list
基本棧操作
1 #735
2 #Runtime: 98 ms (Beats 14.98%)
3 #Memory: 14.6 MB (Beats 16.21%)
4
5 class Solution(object):
6 def asteroidCollision(self, asteroids):
7 """
8 :type asteroids: List[int]
9 :rtype: List[int]
10 """
11 stk = [asteroids[0]]
12 for x in asteroids[1:]:
13 stk.append(x)
14 while len(stk) > 1 and stk[-2] > 0 and stk[-1] < 0:
15 pre1 = stk[-1]
16 pre2 = stk[-2]
17 stk.pop()
18 stk.pop()
19 if abs(pre1) != abs(pre2):
20 stk.append(pre1) if abs(pre1) > abs(pre2) else stk.append(pre2)
21 return stk