力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
为了满足更多的小孩,就不要造成饼干尺寸的浪费。
大尺寸的饼干既可以满足胃口大的孩子也可以满足胃口小的孩子,那么就应该优先满足胃口大的。
这里的局部最优就是大饼干喂给胃口大的,充分利用饼干尺寸喂饱一个,全局最优就是喂饱尽可能多的小孩。
可以尝试使用贪心策略,先将饼干数组和小孩数组排序。
然后从后向前遍历小孩数组,用大饼干优先满足胃口大的,并统计满足小孩数量。
代码:
- class Solution {
- public:
- int findContentChildren(vector<int>& g, vector<int>& s) {
- sort(g.begin(), g.end());
- sort(s.begin(), s.end());
- int index = s.size() - 1;
- int result = 0;
- for(int i = g.size() - 1; i >=0;i--)
- {
- if(index >=0 && s[index]>=g[i])//先判断index>=0
- {
- result++;
- index--;
- }
- }
- return result;
- }
- };