-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsteroidsCollision.java
37 lines (23 loc) · 1008 Bytes
/
AsteroidsCollision.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
class Solution {
//Time: O(n) where n is number of asteroids
//Space: O(n) where n is number of asteroids
public int[] asteroidCollision(int[] asteroids) {
Deque<Integer> remaining = new LinkedList<>();
for(int asteroid: asteroids) {
while(asteroid < 0 && !remaining.isEmpty() && remaining.peekLast() > 0) {
int prev = remaining.pollLast();
if (Math.abs(asteroid) > prev) asteroid = asteroid;
else if (Math.abs(asteroid) < prev) asteroid = prev;
else asteroid = 0;
}
if (asteroid != 0) remaining.addLast(asteroid);
}
int[] sol = new int[remaining.size()];
int idx = 0;
for(Integer asteroid: remaining) {
sol[idx] = asteroid;
idx++;
}
return sol;
}
}