-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path735. 小行星碰撞.java
48 lines (38 loc) · 1.36 KB
/
735. 小行星碰撞.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.Stack;
public class Main {
public static int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int asteroid : asteroids) {
boolean exploded = false;
while (!stack.isEmpty() && asteroid < 0 && stack.peek() > 0) {
if (stack.peek() < -asteroid) {
stack.pop();
continue;
} else if (stack.peek() == -asteroid) {
stack.pop();
}
exploded = true;
break;
}
if (!exploded) {
stack.push(asteroid);
}
}
int[] result = new int[stack.size()];
for (int i = stack.size() - 1; i >= 0; i--) {
result[i] = stack.pop();
}
return result;
}
public static void main(String[] args) {
int[] asteroids1 = {5, 10, -5};
int[] result1 = asteroidCollision(asteroids1);
System.out.println(java.util.Arrays.toString(result1));
int[] asteroids2 = {8, -8};
int[] result2 = asteroidCollision(asteroids2);
System.out.println(java.util.Arrays.toString(result2));
int[] asteroids3 = {10, 2, -5};
int[] result3 = asteroidCollision(asteroids3);
System.out.println(java.util.Arrays.toString(result3));
}
}