|
1 | 1 | package g2101_2200.s2126_destroying_asteroids; |
2 | 2 |
|
3 | | -// #Medium #Array #Sorting #Greedy #2022_06_03_Time_25_ms_(83.82%)_Space_54.6_MB_(93.38%) |
4 | | - |
5 | | -import java.util.Arrays; |
| 3 | +// #Medium #Array #Sorting #Greedy #2022_06_08_Time_6_ms_(99.27%)_Space_54.1_MB_(97.81%) |
6 | 4 |
|
7 | 5 | public class Solution { |
8 | 6 | public boolean asteroidsDestroyed(int mass, int[] asteroids) { |
9 | | - Arrays.sort(asteroids); |
10 | | - long m = mass; |
11 | | - for (int ele : asteroids) { |
12 | | - if (m < ele) { |
13 | | - return false; |
| 7 | + return helper(mass, 0, asteroids); |
| 8 | + } |
| 9 | + |
| 10 | + private boolean helper(long mass, int startIndex, int[] asteroids) { |
| 11 | + int smallOrEqualIndex = partition(mass, startIndex, asteroids); |
| 12 | + if (smallOrEqualIndex < startIndex) { |
| 13 | + return false; |
| 14 | + } |
| 15 | + if (smallOrEqualIndex >= asteroids.length - 1) { |
| 16 | + return true; |
| 17 | + } |
| 18 | + for (int i = startIndex; i <= smallOrEqualIndex; ++i) { |
| 19 | + mass += asteroids[i]; |
| 20 | + } |
| 21 | + return helper(mass, ++smallOrEqualIndex, asteroids); |
| 22 | + } |
| 23 | + |
| 24 | + private int partition(long mass, int startIndex, int[] asteroids) { |
| 25 | + int length = asteroids.length; |
| 26 | + int smallOrEqualIndex = startIndex - 1; |
| 27 | + for (int i = startIndex; i < length; ++i) { |
| 28 | + if (asteroids[i] <= mass) { |
| 29 | + smallOrEqualIndex++; |
| 30 | + swap(asteroids, i, smallOrEqualIndex); |
14 | 31 | } |
15 | | - m += ele; |
16 | 32 | } |
17 | | - return true; |
| 33 | + return smallOrEqualIndex; |
| 34 | + } |
| 35 | + |
| 36 | + private void swap(int[] array, int i, int j) { |
| 37 | + int tmp = array[i]; |
| 38 | + array[i] = array[j]; |
| 39 | + array[j] = tmp; |
18 | 40 | } |
19 | 41 | } |
0 commit comments