0

2126、摧毁小行星 | 算法(leetode,附思维导图 + 全部解法)300题

 2 years ago
source link: https://segmentfault.com/a/1190000041358255
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

零 标题:算法(leetode,附思维导图 + 全部解法)300题之(2126)摧毁小行星

一 题目描述

二 解法总览(思维导图)

三 全部解法

1)代码:

// 方案1 “排序、模拟法(本质:贪心法)”。
// 技巧:“类似打怪升级,优先打败小怪物、升级,后面再去挑战血量更厚的怪物!”。

// 思路:
// 1)状态初始化,resBool = true 。
// 2)核心1:对 asteroids 进行升序排序。
// 3)核心2:遍历 asteroids ,根据情况分别去更新 mass、resBool 值。
// 3.1)若  mass >= asteroids[i] (说明行星 能摧毁该小行星),
// 则 mass += asteroids[i] (获得该小行星的质量)。
// 3.2)若  mass < asteroids[i] (说明行星 不能摧毁该小行星),
// 则 resBool = false 并 跳出循环 。
// 4)返回结果 resBool 。
var asteroidsDestroyed = function(mass, asteroids) {
    // 1)状态初始化,resBool = true 。
    const l = asteroids.length;
    let resBool = true;

    // 2)核心1:对 asteroids 进行升序排序。
    asteroids = asteroids.sort((a, b) => a - b);
    
    // 3)核心2:遍历 asteroids ,根据情况分别去更新 mass、resBool 值。
    for (let i = 0; i < l; i++) {
        // 3.1)若  mass >= asteroids[i] (说明行星 能摧毁该小行星),
        // 则 mass += asteroids[i] (获得该小行星的质量)。
        if (mass >= asteroids[i]) {
            mass += asteroids[i];
        }
        // 3.2)若  mass < asteroids[i] (说明行星 不能摧毁该小行星),
        // 则 resBool = false 并 跳出循环 。
        else {
            resBool = false;
            break;
        }
    }

    // 4)返回结果 resBool 。
    return resBool;
};

1)代码:

// 方案2 “一行代码 - 装X法”。
// 技巧:通过 数组的sort方法,对 asteroids 进行升序排序(“体现贪心”);
// 通过 数组的reduce(n个元素 变成 1个元素,优先考虑使用 reduce )方法,不断遍历每个小行星(从小到大)、不断更新 acc 和 mass值。
var asteroidsDestroyed = function(mass, asteroids) {
    return asteroids.sort((a, b) => a - b).reduce(
        (acc, cur) => (acc) && (mass >= cur ? (mass += cur) : (0)),
        true
    );
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK