-
Notifications
You must be signed in to change notification settings - Fork 7
/
Main.java
28 lines (24 loc) · 802 Bytes
/
Main.java
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
package com.company;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
// write your code here
}
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int a : asteroids) {
if (stack.empty() || a > 0)
stack.push(a);
else {
while (!stack.isEmpty() && a * stack.peek() < 0 && stack.peek() < -a)
stack.pop();
if (stack.empty() || stack.peek() < 0) stack.push(a);
else if (stack.peek() == -a) stack.pop();
}
}
int[] res = new int[stack.size()];
for (int i = res.length - 1; i >= 0; i--)
res[i] = stack.pop();
return res;
}
}