forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0735-asteroid-collision.java
34 lines (32 loc) · 1012 Bytes
/
0735-asteroid-collision.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
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
int index = 0;
while(index < asteroids.length) {
int a = asteroids[index];
if(stack.isEmpty()) {
stack.push(a);
index++;
} else {
if(stack.peek() > 0 && a < 0) {
if(Math.abs(stack.peek()) > Math.abs(a)) {
index++;
} else if(Math.abs(stack.peek()) < Math.abs(a)) {
stack.pop();
} else {
index++;
stack.pop();
}
} else {
stack.push(a);
index++;
}
}
}
int[] res = new int[stack.size()];
for(int i=res.length-1; i>=0 ;i--) {
res[i] = stack.pop();
}
return res;
}
}