455. Assign Cookies

Leetcode 問題: 455. Assign Cookies

題目

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.

Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

傳入兩個陣列,第一個 小孩陣列,每個數字代表那個小孩 想要的餅乾數量

[1,3,5] 代表

小孩索引 0 1 2
想要的餅乾數量 1 3 5

第二個陣列代表 餅乾盤陣列,每個數字代表 那一個盤子有幾個餅乾

[3,5,7] 代表

餅乾盤索引 0 1 2
有多少餅乾 3 5 7

目標是要盡可能將所有小孩餵飽,滿足他想要的餅乾,並找出最多能滿足幾個小孩

Example

Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
Input: g = [1,2], s = [1,2,3]
Output: 2
Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.

答案

  • 盡量用最少的餅乾數量餵飽需求最少的小孩,所以要先餵飽滿足度較低的小孩

JavaScript

  1. 小孩陣列餅乾盤陣列 由小到大排序
    • 確保 小孩陣列 前面都是滿足度較低的小孩
    • 確保 餅乾盤陣列 前面都是餅乾數較少的盤子
  2. 設定 小孩檢查指標 到第一個滿足度較低的小孩索引 0 並 設定 餅乾盤檢查指標 到第一個餅乾數最少的餅乾盤索引 0
    • 當目前 小孩檢查指標 的小孩能夠滿足,後面的小孩才有可能滿足
    • 當目前 小孩檢查指標 無法滿足,後面的小孩也不用檢查,肯定吃不飽
  3. 小孩檢查指標 的小孩需要的餅乾,是 餅乾盤檢查指標 的餅乾數可以滿足的話
    • 找到一個可以餵飽的小孩了
    • 繼續檢查下一個小孩
    • 繼續用下一個餅乾盤檢查是否能夠餵飽小孩
  4. 小孩檢查指標 的小孩需要的餅乾,在 餅乾盤檢查指標 的餅乾數無法滿足
    • 繼續找下一個餅乾盤,看後面的餅乾盤有沒有足夠的數量可以餵飽小孩
/**
 * @param {number[]} childrenList
 * @param {number[]} cookieList
 * @return {number}
 */
var findContentChildren = function(childrenList, cookieList) {
    // 將小孩需要的餅乾數量,依照小到大排序
    childrenList.sort((a, b) => {
        return a - b;
    });

    // 將擁有餅乾盤子數量,依照小到大排序
    cookieList.sort((a, b) => {
        return a - b;
    });

    // 小孩檢查指標
    let childPointer = 0;
    // 餅乾盤檢查指標
    let cookiePointer = 0;

    while (childPointer < childrenList.length && cookiePointer < cookieList.length) {
        // 當還沒有檢查完所有小孩,且也還沒檢查完所有餅乾盤子,繼續檢查
        if (childrenList[childPointer] <= cookieList[cookiePointer]) {
            // 當目前的餅乾盤,可以餵飽小孩,繼續找下一個
            childPointer++;
            cookiePointer++;
        } else {
            // 當目前的餅乾盤,無法餵飽小孩,繼續找下一個
            cookiePointer++;
        }
    }

    return childPointer;
};

參考資料