Leetcode-Algorithm-Greedy-455
-
题目:
-
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.
(给孩子们分饼干,每个孩子最多只能拿一块饼干,每个孩子都有使他们自己满意的饼干大小gi,即令饼干的大小为sj,当 sj>=gi 时,才能使孩子满意。求给定孩子们的饼干的满意大小以及分配的饼干的大小的情况下,最多能使多少个孩子满意。)
注意:
-
假定使孩子们满意的饼干大小总是正数。
每个孩子最多只有一块饼干。
例子:
输入:[1,2,3], [1,1]
输出:1
输入:[1,2], [1,2,3]
输出:2
题解:
方法:(贪心算法)
首先我们应该理解,饼干越大,能够满足的小孩的个数就越多,而饼干越小,能满足的小孩就越局限。因此,如果用很大的饼干去满足一个只需要很小的饼干的小孩的话,这样无疑是一种“浪费“,因为这个饼干可以满足需求更大的小孩。若用于需求小的小孩那么后面需求大的小孩很有可能就得不到满足,而且小的饼干也有可能被浪费。因此最理想的情况是,把小的饼干给需求小的孩子,把大的饼干给需求大的孩子,这样才能尽可能多地满足孩子。所以在每一次“选择”,都需要把“最小”的饼干给需求“最小”的孩子,后面重复这样的选择就能得到其中一个最优解,这就是贪心算法。
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
int count = 0;
vector<int>::iterator giter = g.begin();
vector<int>::iterator siter = s.begin();
sort(giter, g.end());
sort(siter, s.end());
while (giter != g.end() && siter != s.end()) {
if (*giter <= *siter) {
++count;
++giter;
++siter;
}
else
++siter;
}
return count;
}
};
分析:
代码里用的排序函数的平均时间复杂度为
O(nlogn)
,之后设置两个指针来遍历两个容器,时间复杂度为
O(n)
,综上可知,这个算法的时间复杂度在于容器的排序,所以时间复杂度为
O(nlogn)
。