LeetCode每日一题(2126. Destroying Asteroids)

给定一个表示行星质量的整数和一个表示小行星质量的数组,行星可以按任意顺序与小行星碰撞。如果行星的质量大于或等于小行星,小行星被摧毁,行星增加小行星的质量。返回行星能否摧毁所有小行星。示例展示了一种判断方法:先对小行星数组排序,然后从小到大依次碰撞。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid.

You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed.

Return true if all asteroids can be destroyed. Otherwise, return false.

Example 1:

Input: mass = 10, asteroids = [3,9,19,5,21]
Output: true

Explanation: One way to order the asteroids is [9,19,5,3,21]:

  • The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19
  • The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38
  • The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43
  • The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46
  • The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67

All asteroids are destroyed.

Example 2:

Input: mass = 5, asteroids = [4,9,23,4]
Output: false

Explanation:
The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.
After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.
This is less than 23, so a collision would not destroy the last asteroid.

Constraints:

  • 1 <= mass <= 10^5
  • 1 <= asteroids.length <= 10^5
  • 1 <= asteroids[i] <= 10^5

将 asteroids 排序, 然后从小到大碰过去就好了


impl Solution {
    pub fn asteroids_destroyed(mass: i32, mut asteroids: Vec<i32>) -> bool {
        let mut mass = mass as i64;
        asteroids.sort();
        for a in asteroids {
            if a as i64 > mass {
                return false;
            }
            mass += a as i64;
        }
        true
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值