-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsteroidCollision.java
More file actions
46 lines (35 loc) · 1.25 KB
/
Copy pathAsteroidCollision.java
File metadata and controls
46 lines (35 loc) · 1.25 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
43
44
45
46
package LeetcodePractice;
import java.util.Stack;
public class AsteroidCollision {
public static int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int ast : asteroids) {
while (!stack.isEmpty() && ast < 0 && stack.peek() > 0) {
if (stack.peek() < -ast) {
stack.pop();
continue;
} else if (stack.peek() == -ast) {
stack.pop();
}
ast = 0;
break;
}
if (ast != 0) {
stack.push(ast);
}
}
int[] result = new int[stack.size()];
for (int i = result.length - 1; i >= 0; i--) {
result[i] = stack.pop();
}
return result;
}
public static void main(String[] args) {
int[] asteroids1 = {5, 10, -5};
System.out.println(asteroidCollision(asteroids1));
int[] asteroids2 = {8, -8};
System.out.println(asteroidCollision(asteroids2));
int[] asteroids3 = {10, 2, -5};
System.out.println(asteroidCollision(asteroids3));
}
}