
题目描述
给你一个整数 mass
,它表示一颗行星的初始质量。再给你一个整数数组 asteroids
,其中 asteroids[i]
是第 i
颗小行星的质量。
你可以按 任意顺序 重新安排小行星的顺序,然后让行星跟它们发生碰撞。如果行星碰撞时的质量 大于等于 小行星的质量,那么小行星被 摧毁 ,并且行星会 获得 这颗小行星的质量。否则,行星将被摧毁。
如果所有小行星 都 能被摧毁,请返回 true
,否则返回 false
。
示例 1:
输入:mass = 10, asteroids = [3,9,19,5,21]
输出:true
解释:一种安排小行星的方式为 [9,19,5,3,21] :
- 行星与质量为 9 的小行星碰撞。新的行星质量为:10 + 9 = 19
- 行星与质量为 19 的小行星碰撞。新的行星质量为:19 + 19 = 38
- 行星与质量为 5 的小行星碰撞。新的行星质量为:38 + 5 = 43
- 行星与质量为 3 的小行星碰撞。新的行星质量为:43 + 3 = 46
- 行星与质量为 21 的小行星碰撞。新的行星质量为:46 + 21 = 67
所有小行星都被摧毁。
示例 2:
输入:mass = 5, asteroids = [4,9,23,4]
输出:false
解释:
行星无论如何没法获得足够质量去摧毁质量为 23 的小行星。
行星把别的小行星摧毁后,质量为 5 + 4 + 9 + 4 = 22 。
它比 23 小,所以无法摧毁最后一颗小行星。
提示:
1 <= mass <= 105
1 <= asteroids.length <= 105
1 <= asteroids[i] <= 105
解法
方法一:排序 + 贪心
根据题目描述,我们可以将小行星按质量从小到大排序,然后依次遍历小行星,如果行星的质量小于小行星的质量,那么行星将被摧毁,返回 false
,否则行星将获得这颗小行星的质量。
如果所有小行星都能被摧毁,返回 true
。
时间复杂度 \(O(n \times \log n)\),空间复杂度 \(O(\log n)\)。其中 \(n\) 是小行星的数量。
| class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort()
for x in asteroids:
if mass < x:
return False
mass += x
return True
|
1
2
3
4
5
6
7
8
9
10
11
12
13 | class Solution {
public boolean asteroidsDestroyed(int mass, int[] asteroids) {
Arrays.sort(asteroids);
long m = mass;
for (int x : asteroids) {
if (m < x) {
return false;
}
m += x;
}
return true;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | class Solution {
public:
bool asteroidsDestroyed(int mass, vector<int>& asteroids) {
ranges::sort(asteroids);
long long m = mass;
for (int x : asteroids) {
if (m < x) {
return false;
}
m += x;
}
return true;
}
};
|
| func asteroidsDestroyed(mass int, asteroids []int) bool {
sort.Ints(asteroids)
for _, x := range asteroids {
if mass < x {
return false
}
mass += x
}
return true
}
|
| function asteroidsDestroyed(mass: number, asteroids: number[]): boolean {
asteroids.sort((a, b) => a - b);
for (const x of asteroids) {
if (mass < x) {
return false;
}
mass += x;
}
return true;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13 | impl Solution {
pub fn asteroids_destroyed(mass: i32, mut asteroids: Vec<i32>) -> bool {
let mut mass = mass as i64;
asteroids.sort_unstable();
for &x in &asteroids {
if mass < x as i64 {
return false;
}
mass += x as i64;
}
true
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | /**
* @param {number} mass
* @param {number[]} asteroids
* @return {boolean}
*/
var asteroidsDestroyed = function (mass, asteroids) {
asteroids.sort((a, b) => a - b);
for (const x of asteroids) {
if (mass < x) {
return false;
}
mass += x;
}
return true;
};
|