forked from sammorozov/1337Code_tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path735. Asteroid Collision.py
94 lines (59 loc) · 2.29 KB
/
735. Asteroid Collision.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from typing import *
# class Solution:
# def asteroidCollision(self, asteroids: List[int]) -> List[int]:
# for i in range(len(asteroids)):
# if asteroids[i] < 0:
# j = i-1
# while j != 0:
# if asteroids[j] > 0:
# if abs(asteroids[i]) > abs(asteroids[j]):
# asteroids[j] = asteroids[i]
# asteroids[i] = 0
# j -= 1
# elif abs(asteroids[i]) < abs(asteroids[j]):
# asteroids[i] = 0
# else:
# asteroids[i] = 0
# asteroids[j] = 0
# return asteroids
# print(Solution().asteroidCollision(asteroids = [10,2,-5]))
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
result = []
for i in asteroids:
if i > 0:
stack.append(i)
elif i < 0 and len(stack) > 0:
if stack[-1] > abs(i):
continue
elif stack[-1] <= abs(i):
if stack[-1] == abs(i):
stack.pop()
break
else:
while stack[-1] < abs(i):
stack.pop()
if len(stack) == 0:
result.append(i)
break
if len(stack) != 0 and stack[-1] == abs(i):
stack.pop()
elif i < 0 and len(stack) == 0:
result.append(i)
return result + stack
class Solution2:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for asteroid in asteroids:
while stack and asteroid < 0 < stack[-1]:
if stack[-1] < -asteroid:
stack.pop()
continue
elif stack[-1] == -asteroid:
stack.pop()
break
else:
stack.append(asteroid)
return stack
print(Solution2().asteroidCollision(asteroids = [-2,2,1,-2]))