Shu-How Zの小窝

Loading...

LeetCode:455.分饼干

LeetCode:455.分饼干

解题思路局部最优:既能满足孩子,还消耗最少。先将“较小的饼干”分给“胃囗最小”的孩子。

解题步骤对饼干数组和胃口数组升序排序。遍历饼干数组,找到能满足第一个孩子的饼干。然后继续遍历饼干数组,找到满足第二、三、….、n个孩子的饼干。

/**
 * @param {number[]} g
 * @param {number[]} s
 * @return {number}
 */
var findContentChildren = function(g, s) {
    g.sort((a, b) => a - b)
    s.sort((a, b) => a - b)
    let i=0;
    s.forEach(item=>{
        if(item>=g[i]){
            i++
        }
    })
    return i
};
// let g = [1,2,3], s = [1,1]
let g = [1,2], s = [1,2,3]
console.log(findContentChildren(g, s)) //1

'

posted @ 2025-01-18 22:24  KooTeam  阅读(14)  评论(0)    收藏  举报