返回介绍

solution / 2100-2199 / 2126.Destroying Asteroids / README_EN

发布于 2024-06-17 01:03:09 字数 3699 浏览 0 评论 0 收藏 0

2126. Destroying Asteroids

中文文档

Description

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 <= 105
  • 1 <= asteroids.length <= 105
  • 1 <= asteroids[i] <= 105

Solutions

Solution 1

class Solution:
  def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
    asteroids.sort()
    for v in asteroids:
      if mass < v:
        return False
      mass += v
    return True
class Solution {
  public boolean asteroidsDestroyed(int mass, int[] asteroids) {
    Arrays.sort(asteroids);
    long m = mass;
    for (int v : asteroids) {
      if (m < v) {
        return false;
      }
      m += v;
    }
    return true;
  }
}
class Solution {
public:
  bool asteroidsDestroyed(int mass, vector<int>& asteroids) {
    sort(asteroids.begin(), asteroids.end());
    long long m = mass;
    for (int v : asteroids) {
      if (m < v) return false;
      m += v;
    }
    return true;
  }
};
func asteroidsDestroyed(mass int, asteroids []int) bool {
  m := mass
  sort.Ints(asteroids)
  for _, v := range asteroids {
    if m < v {
      return false
    }
    m += v
  }
  return true
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文