|
1 | 1 | classSolution {
|
2 |
| -publicint[]asteroidCollision(int[]asteroids) { |
3 |
| -Stack<Integer>stack =newStack<>(); |
4 |
| -for (intasteroid :asteroids) { |
5 |
| -if (asteroid <0) { |
6 |
| -while (!stack.isEmpty() &&stack.peek() >0 &&stack.peek() <Math.abs(asteroid)) { |
7 |
| -stack.pop(); |
| 2 | +publicint[]asteroidCollision(int[]asteroids) { |
| 3 | +List<Integer>result =newArrayList<>(); |
| 4 | +intidx =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 | +returnresult.stream().mapToInt(Integer::valueOf).toArray(); |
19 | 32 | }
|
20 |
| -int[]result =newint[stack.size()]; |
21 |
| -for (inti =result.length -1;i >=0;i--) { |
22 |
| -result[i] =stack.pop(); |
23 |
| - } |
24 |
| -returnresult; |
25 |
| - } |
26 | 33 | }
|