题目:
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
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.
分析:
这道题是一个典型的贪心策略的使用的题目,要让最多的children得到饼干,就要尽可能满足需求小的children,直到饼干用完或者最大块的饼干已不能满足当前需求最小的child。
具体步骤:
- step1:写一个归并排序函数,分别对children和cookies进行从小到大的归并排序,时间复杂度位O(nlogn)。
- step2:用贪心策略,对饼干从小到大找能满足当前要求最低的小朋友的那一块,其中i,j作为指针指向饼干和小朋友的最小值往后进行遍历,时间复杂度为O(n)。
- step3:返回满足要求的children数量,总时间复杂度为O(nlogn)。
/*归并排序合并步骤*/
vector<int> merge(vector<int> v1, vector<int> v2){
vector<int> v;
int i = 0, j = 0;
while (i != v1.size() && j != v2.size()){
if (v1[i] < v2[j]){
v.push_back(v1[i]);
i++;
}
else{
v.push_back(v2[j]);
j++;
}
}
if (i == v1.size()){
while (j != v2.size()){
v.push_back(v2[j]);
j++;
}
}
else{
while (i != v1.size()){
v.push_back(v1[i]);
i++;
}
}
return v;
}
/*归并排序递归*/
vector<int> re_sort(vector<int>& v, int s, int e){
if (s >= e){
vector<int> v1(1, v[s]);
return v1;
}
int mid = (s + e) / 2;
return merge(re_sort(v, s, mid), re_sort(v, mid + 1, e));
}
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
if (s.empty() || g.empty()) return 0; //排除掉g和s为空的情况
vector<int> g1 = re_sort(g, 0, g.size() - 1); //对children归并排序,时间O(nlogn)
vector<int> s1 = re_sort(s, 0, s.size() - 1); //对cookies归并排序,时间O(nlogn)
int i = 0, j = 0, count = 0;
/*贪心策略,对饼干从小到大找能满足当前要求最低的小朋友的那一块*/
while (i <= g1.size() - 1 && j <= s1.size() - 1){
if (s1[j] >= g1[i]){ //i,j分别是指向饼干和小朋友的指针
count++;
i++;
}
j++;
}
return count; //返回满足要求的children数量
}
};