LeetCode455. Assign Cookies题解

来源:互联网 发布:淘宝网耐克男特价 编辑:程序博客网 时间:2024/06/17 22:49

题目:
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.

大意是给你两个数组,第一个数组是每个孩子需要的饼干数,第二个数组是你每次有的饼干个数,问最多能满足几个孩子?

思路:
首先将两个数组从小到大排序。遍历第二个数组,当你有的饼干数不下于孩子需要的个数,则可以满足他。注意跳出循环的时间。

代码如下:

class Solution {public:    int findContentChildren(vector<int>& g, vector<int>& s) {        sort(g.begin(), g.end());        sort(s.begin(), s.end());        int ans = 0,j = 0;        for(int i = 0;i < s.size();i++){            if(s[i] >= g[j]){                ans++;                j++;                if (j >= g.size()) break;            }        }        return ans;    }};
原创粉丝点击