玩命加载中 . . .

455-分发饼干


LeetCode 455. Assign Cookies

LeetCode-455

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.

Example 1:

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.

method: 贪心

先排序

从大往小遍历,用大的饼干先去满足大的需求

int findContentChildren(vector<int>& g, vector<int>& s) {
    sort(g.begin(), g.end());
    sort(s.begin(), s.end());
    int res = 0;
    int index = s.size() - 1;   // 用index遍历就不需要嵌套for
    for (int i = g.size() - 1; i >= 0; i--) {
        if (index >= 0 && s[index] >= g[i]) {
            index--;
            res++;
        }
    }
    return res;
}

也可以从小往大遍历,用小的饼干先去满足小的需求

int findContentChildren(vector<int>& g, vector<int>& s) {
    sort(g.begin(), g.end());
    sort(s.begin(), s.end());
    int index = 0;
    for (int i = 0; i < s.size(); i++) {
        if (index < g.size() && g[index] <= s[i]) {
            index++;
        }
    }
    return index;   // 有几个被满足了就是结果
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录