Leetcode 455. Assign Cookies
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: 1
Example 2:
Input: [1,2], [1,2,3]
Output: 2
题目大意:
假设您是一位了不起的父母,并想给您的孩子一些饼干。但是,您最多可以给每个孩子一个cookie。 每个孩子i都有一个贪婪因子gi为孩子满意的cookie的最小大小;每个cookie j的大小均为sj。 如果sj >= gi,我们可以将cookie j分配给孩子i,其将得到满足。目标是最大程度地增加得到满足孩子的数量并输出最大数量。注意:gi始终为正且不能为一个孩子分配多个cookie。
解题思路:
对两个数组进行由小到大排序,贪心策略满足尽可能多的孩子,设置两个指针遍历两个数组,满足则s,g指针同时后移,不满足则s指针后移。返回g指针的位置即为已满足的孩子个数。时间复杂度为O(m+n)。
代码:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int i = 0, j = 0;
while(i < g.size() && j < s.size())
{
if(s[j] >= g[i])
{
i++; j++;
}
else
j++;
}
return i;
}
};
本文详细解析了LeetCode上的经典问题——分发饼干问题(LeetCode 455),介绍了如何通过排序和贪心策略来解决这个问题,以最大化满足孩子需求的数量。文章提供了清晰的代码实现,帮助读者理解并掌握此题的解决方法。
1157

被折叠的 条评论
为什么被折叠?



