【LeetCode】455. Assign Cookies
来源:互联网 发布:英语软件有哪些 编辑:程序博客网 时间:2024/05/20 10:55
题目:
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.
Example 1:
Input: [1,2,3], [1,1]Output: 1Explanation: 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.
Example 2:
Input: [1,2], [1,2,3]Output: 2Explanation: 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.
题解:
先把两个vector升序排列,这样再从头遍历,当cookie遍历完就结束。要注意遍历到cookie最后一项时,满足要求和不满足要求两种情况的处理。还有,当g[i]<=s[k]时,如果直接break,k并没有+1,就会导致重复遍历了一个cookie。
答案:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int result=0;
int k=0;
bool even=true;
for(int i=0;i<g.size();i++)
{
for(;k<s.size();k++)
{
if(g[i]<=s[k])
{
result++;
if(k!=s.size()-1)
k++;
else
even=false;
break;
}
else if(k==s.size()-1)
{
even=false;
break;
}
}
if(!even)
break;
}
return result;
}
};
- LeetCode 455. Assign Cookies
- Leetcode-455. Assign Cookies
- LeetCode 455. Assign Cookies
- 【LeetCode】455. Assign Cookies
- leetcode 455. Assign Cookies
- 455. [LeetCode]Assign Cookies
- [leetcode] 455. Assign Cookies
- 【LeetCode】 455. Assign Cookies
- [LeetCode]455. Assign Cookies
- Leetcode-455. Assign Cookies
- LeetCode 455. Assign Cookies
- LeetCode 455. Assign Cookies
- 455. Assign Cookies [LeetCode]
- leetcode 455. Assign Cookies
- 【Leetcode】455. Assign Cookies
- LeetCode 455. Assign Cookies
- LeetCode | 455. Assign Cookies
- leetcode.455.Assign Cookies
- PopUpWindow使用详解(一)——基本使用
- HDOJ 1527 取石子游戏(威佐夫博奕)
- HDU 5816 Hearthstone (Probability dp, Conbinations)
- 微服务与SOA之间差了一个ESB
- Android开源库V
- 【LeetCode】455. Assign Cookies
- PopUpWindow使用详解(二)——进阶及答疑
- caffe python 接口文档汇总
- Tree-----判断tree是不是BST(110. Balanced Binary Tree)
- HDOJ 1282 回文数猜想
- JAVA设计模式之工厂模式之抽象工厂模式
- 策略模式
- Android的帧动画、补间动画、属性动画
- 动态规划石子合并问题