-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0735-AsteroidCollision.cs
45 lines (38 loc) · 1.27 KB
/
0735-AsteroidCollision.cs
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
//-----------------------------------------------------------------------------
// Runtime: 264ms
// Memory Usage: 33 MB
// Link: https://leetcode.com/submissions/detail/373718130/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0735_AsteroidCollision
{
public int[] AsteroidCollision(int[] asteroids)
{
var stack = new Stack<int>();
foreach (var asteroid in asteroids)
{
var explodeBoth = false;
while (stack.Count > 0 && asteroid < 0 && stack.Peek() > 0)
{
if (stack.Peek() + asteroid < 0)
{
stack.Pop();
continue;
}
else if (stack.Peek() + asteroid == 0)
stack.Pop();
explodeBoth = true;
break;
}
if (!explodeBoth)
stack.Push(asteroid);
}
var result = new int[stack.Count];
for (int i = stack.Count - 1; i >= 0; i--)
result[i] = stack.Pop();
return result;
}
}
}