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可以累加,那么问题就复杂了很多。

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