Example 1:
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.
Example 2:
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.
题目大意:
假设你是一个了不起的家长,想给你的孩子一些饼干。但是,你应该给每个孩子最多一个饼干。每个孩子我都有一个贪婪因子gi,这是孩子满意的一个cookie的最小大小;每个Cookie j有一个大小Sj。如果sj>=gi,我们可以将cookie j分配给子表i,而子表i将满足。您的目标是最大限度地增加内容子程序的数量,并输出最大数量的内容。
解题思路:
典型的贪心算法题,有两种常见的解题思路,
①先尝试满足最贪心的小朋友
②先尝试满足最不贪心的小朋友
#include
#include
#include
using namespace std;
/// 455. Assign Cookies
/// https://leetcode.com/problems/assign-cookies/description/
/// 先尝试满足最贪心的小朋友
/// 时间复杂度: O(nlogn)
/// 空间复杂度: O(1)
class Solution {
public:
int findContentChildren(vector& g, vector& s) {
sort(g.begin(), g.end(), greater());
sort(s.begin(), s.end(), greater());
int gi = 0, si = 0;
int res = 0;
while(gi < g.size() && si < s.size()){
if(s[si] >= g[gi]){
res ++;
si ++;
gi ++;
}
else
gi ++;
}
return res;
}
};
int main() {
int g1[] = {1, 2, 3};
vector gv1(g1, g1 + sizeof(g1)/sizeof(int));
int s1[] = {1, 1};
vector sv1(s1, s1 + sizeof(s1)/sizeof(int));
cout << Solution().findContentChildren(gv1, sv1) << endl;
int g2[] = {1, 2};
vector gv2(g2, g2 + sizeof(g2)/sizeof(int));
int s2[] = {1, 2, 3};
vector sv2(s2, s2 + sizeof(s2)/sizeof(int));
cout << Solution().findContentChildren(gv2, sv2) << endl;
return 0;
}
#include
#include
#include
using namespace std;
/// 455. Assign Cookies
/// https://leetcode.com/problems/assign-cookies/description/
/// 先尝试满足最不贪心的小朋友
/// 时间复杂度: O(nlogn)
/// 空间复杂度: O(1)
class Solution {
public:
int findContentChildren(vector& g, vector& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int gi = 0, si = 0;
int res = 0;
while(gi < g.size() && si < s.size()){
if(s[si] >= g[gi]){
res ++;
si ++;
gi ++;
}
else
si ++;
}
return res;
}
};
int main() {
int g1[] = {1, 2, 3};
vector gv1(g1, g1 + sizeof(g1)/sizeof(int));
int s1[] = {1, 1};
vector sv1(s1, s1 + sizeof(s1)/sizeof(int));
cout << Solution().findContentChildren(gv1, sv1) << endl;
int g2[] = {1, 2};
vector gv2(g2, g2 + sizeof(g2)/sizeof(int));
int s2[] = {1, 2, 3};
vector sv2(s2, s2 + sizeof(s2)/sizeof(int));
cout << Solution().findContentChildren(gv2, sv2) << endl;
return 0;
}