-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsteroid Collision.java
More file actions
32 lines (31 loc) · 1.03 KB
/
Asteroid Collision.java
File metadata and controls
32 lines (31 loc) · 1.03 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
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stk = new Stack<>();
for (int i = 0; i < asteroids.length; i++) {
if (stk.isEmpty()) {
stk.push(asteroids[i]);
} else if (asteroids[i] > 0) {
stk.push(asteroids[i]);
} else if (asteroids[i] < 0) {
int curr = asteroids[i];
while (curr < 0 && !stk.isEmpty() && stk.peek() > 0) {
int val = stk.pop();
if (curr + val < 0) {
curr = curr;
} else if (curr + val > 0) {
curr = val;
} else {
curr = 0;
}
}
if (curr != 0)
stk.push(curr);
}
}
int[] result = new int[stk.size()];
for(int i=result.length - 1;i>=0;i--){
result[i] = stk.pop();
}
return result;
}
}