-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsteroid_Collision.java
35 lines (30 loc) · 1.23 KB
/
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
35
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int asteroid : asteroids) {
boolean destroyed = false;
// Handle collisions only when there's a right-moving asteroid in the stack and a left-moving asteroid in the current one
while (!stack.isEmpty() && stack.peek() > 0 && asteroid < 0) {
if (Math.abs(stack.peek()) < Math.abs(asteroid)) {
stack.pop(); // The asteroid in the stack is destroyed
} else if (Math.abs(stack.peek()) == Math.abs(asteroid)) {
stack.pop(); // Both are destroyed
destroyed = true;
break;
} else {
destroyed = true; // Current asteroid is destroyed
break;
}
}
if (!destroyed) {
stack.push(asteroid); // Push only if it survives
}
}
// Convert stack to array
int[] result = new int[stack.size()];
for (int i = stack.size() - 1; i >= 0; i--) {
result[i] = stack.pop();
}
return result;
}
}