/
AsteroidCollision.java
54 lines (47 loc) · 1.46 KB
/
AsteroidCollision.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
49
50
51
52
53
54
// https://leetcode.com/problems/asteroid-collision
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
Stack<Integer> unused = new Stack<>();
for (int x: asteroids) {
if (stack.isEmpty()) {
if (x > 0)
stack.push(x);
else
unused.push(x);
} else {
if (sign(x) == sign(stack.peek())) {
stack.push(x);
continue;
}
while (sign(x) != sign(stack.peek())) {
int k = stack.pop();
if (Math.abs(k) > Math.abs(x)) {
stack.push(k);
break;
} else if (Math.abs(k) == Math.abs(x)) {
break;
} else {
if (stack.isEmpty()) {
if (x > 0)
stack.push(x);
else
unused.push(x);
break;
}
}
}
}
}
unused.addAll(stack);
int[] res = new int[unused.size()];
int i = 0;
for (int x: unused) {
res[i++] = x;
}
return res;
}
int sign(int x) {
return x < 0 ? -1: 1;
}
}