-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsteroidCollision.java
More file actions
42 lines (36 loc) · 1.13 KB
/
AsteroidCollision.java
File metadata and controls
42 lines (36 loc) · 1.13 KB
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
package Stacks;
import java.util.Stack;
public class AsteroidCollision {
public static int[] asteroidCollision(int[] asteroids) {
int n = asteroids.length;
Stack<Integer> s = new Stack<>();
for (int asteroid : asteroids) {
if (asteroid > 0 || s.isEmpty()) {
s.push(asteroid);
} else {
while (!s.isEmpty() && s.peek() > 0 && s.peek() < Math.abs(asteroid)) {
s.pop();
}
if (!s.isEmpty() && s.peek() == Math.abs(asteroid)) {
s.pop();
} else {
if (s.isEmpty() || s.peek() < 0) {
s.push(asteroid);
}
}
}
}
int[] res = new int[s.size()];
for (int i = s.size() - 1; i >= 0; i--) {
res[i] = s.pop();
}
return res;
}
public static void main(String[] args) {
int[] asteroids = {5, 10, -5};
int[] ans = asteroidCollision(asteroids);
for (int num : ans) {
System.out.print(num + " ");
}
}
}