Skip to content

Commit 030ccf5

Browse files
committed
Updated Asteroid Collision.java
1 parent 77437e8 commit 030ccf5

File tree

1 file changed

+28
-21
lines changed

1 file changed

+28
-21
lines changed

Medium/Asteroid Collision.java

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,33 @@
11
class Solution {
2-
public int[] asteroidCollision(int[] asteroids) {
3-
Stack<Integer> stack = new Stack<>();
4-
for (int asteroid : asteroids) {
5-
if (asteroid < 0) {
6-
while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < Math.abs(asteroid)) {
7-
stack.pop();
2+
public int[] asteroidCollision(int[] asteroids) {
3+
List<Integer> result = new ArrayList<>();
4+
int idx = 0;
5+
while (idx < asteroids.length && asteroids[idx] < 0) {
6+
result.add(asteroids[idx++]);
87
}
9-
if (!stack.isEmpty() && stack.peek() > 0) {
10-
if (stack.peek() == Math.abs(asteroid)) {
11-
stack.pop();
12-
}
13-
} else {
14-
stack.push(asteroid);
8+
while (idx < asteroids.length) {
9+
if (asteroids[idx] > 0) {
10+
result.add(asteroids[idx++]);
11+
} else {
12+
if (result.isEmpty() || result.get(result.size() - 1) < 0) {
13+
result.add(asteroids[idx]);
14+
} else {
15+
while (!result.isEmpty() &&
16+
result.get(result.size() - 1) > 0 &&
17+
result.get(result.size() - 1) < Math.abs(asteroids[idx])) {
18+
result.remove(result.size() - 1);
19+
}
20+
if (!result.isEmpty() && result.get(result.size() - 1) > 0) {
21+
if (result.get(result.size() - 1) == Math.abs(asteroids[idx])) {
22+
result.remove(result.size() - 1);
23+
}
24+
} else {
25+
result.add(asteroids[idx]);
26+
}
27+
}
28+
idx++;
29+
}
1530
}
16-
} else {
17-
stack.push(asteroid);
18-
}
31+
return result.stream().mapToInt(Integer::valueOf).toArray();
1932
}
20-
int[] result = new int[stack.size()];
21-
for (int i = result.length - 1; i >= 0; i--) {
22-
result[i] = stack.pop();
23-
}
24-
return result;
25-
}
2633
}

0 commit comments

Comments
 (0)