Posted on 2023-07-20 16:01
Uriel 閱讀(37)
評論(0) 編輯 收藏 引用 所屬分類:
模擬 、
數據結構 、
閑來無事重切Leet Code
給出一列數,負數代表向左移動,正數代表向右移動,如果連著的兩個數分別向右和向左,則會碰撞,只剩下絕對值更大的那一個數,問所有碰撞結束之后剩下的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