|
1 | 1 | 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++]); |
8 | 7 | }
|
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 | + } |
15 | 30 | }
|
16 |
| - } else { |
17 |
| - stack.push(asteroid); |
18 |
| - } |
| 31 | + return result.stream().mapToInt(Integer::valueOf).toArray(); |
19 | 32 | }
|
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 |
| - } |
26 | 33 | }
|
0 commit comments