LeetCode455. Assign Cookies題解

1. 題目描述

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 gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, 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.
【NOTE】:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.

2. 樣例

Input: [1,2,3], [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: [1,2], [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.

3. 分析

【理解】:給了兩個輸入的數組,分別代表了每個孩子期待分到的cookie的大小和所擁有的cookie的大小情況。因此第一個數組的長度就是孩子的總數,第二個數組的長度就是cookie的總數。我們需要求出怎麼樣分配:才能使最多數量的孩子對cookie的需求得到滿足
【思路】:我個人覺得用貪心也比較容易想思路:我們將所有的cookie按照大小降序排序,將所有的孩子期待得到cookie的大小也降序排序,接下來兩個數組同時開始遍歷,這樣的做法能夠保證,每一步驟下都可以判斷當前的孩子是否可以滿足心願,因爲當前的cookie也是最大的(比其更大的cookie已經分給了需求更大的孩子)。
如果當前cookie大小大於等於當前孩子的需求:說明這塊cookie是可以滿足條件的,記錄下來;如果當前cookie大小小於當前孩子的需求:那麼說明這個孩子的需求得不到滿足,就只好捨棄他,我們去訪問下一個孩子看看能否滿足他的需求,以求更多的孩子能分到cookie。
這裏寫圖片描述

4. 源碼

class Solution {
public:
    static bool Comp(int a, int b) {
        return (a > b);
    }
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end(), Comp);
        sort(s.begin(), s.end(), Comp);
        int counter = 0;
        int i = 0, j = 0;
        while(i < (int)s.size() && j < (int)g.size()) {
            if (s[i] >= g[j]) {
                counter++;
                i++;
                j++;
            }
            else {
                j++;
            }
        }
        return counter;
    }
};

5. 心得

這道題屬於典型的貪心算法的最簡單應用,之所以簡單是每個孩子最多隻允許被分配一個cookie,如果cookie可以累加,那麼問題就複雜了很多。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章