Assign Cookies
来源:互联网 发布:中国足球知乎 编辑:程序博客网 时间:2024/05/16 14:37
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; }};
分析:
代码里用的排序函数的平均时间复杂度为
0 0
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- Assign Cookies
- LeetCode 455. Assign Cookies
- 455. Assign Cookies
- Leetcode-455. Assign Cookies
- 455. Assign Cookies
- 455. Assign Cookies
- Android Activity 的四种启动模式
- 应用卡顿的常见问题有哪些?
- 颜色控制属性
- Javascript中this的认真理解
- Java NIO(一) 初步理解NIO
- Assign Cookies
- 欢迎使用CSDN-markdown编辑器
- Android开发galleryfinal裁剪png图片问题
- 分类算法之朴素贝叶斯分类(Naive Bayesian classification)
- 实现strcpy函数
- 转载的一道小米面试题和自己的写法
- 海量数据处理算法—Bloom Filter
- 最大流问题:增广路径算法的比较
- 关于360笔试题的一个题目的以下代码执行后输出结果为()思考