要求
- 贪心算法的关键:判断问题是否可以用贪心算法解决
- 给小朋友们分饼干,每个小朋友“贪心指数”为g(i),饼干大小值s(i)
- g(i):小朋友需要的饼干大小的最小值
- 若s(j)>=g(i),则将饼干j分给小朋友i,小朋友会开心
- 给定s、g,问如何分配饼干,能让最多的小朋友开心
示例
- g=[1,2,3], s=[1,1], 输出1
- g=[1,2], s=[1,2,3], 输出2
思路
- 将最大的饼干给最贪心的小朋友
- 先对数组排序
- 复杂度:nlogn
实现
- 从大到小排序
- si:指向饼干
- gi:指向小朋友
- res:记录有多少小朋友开心

1 class Solution { 2 public: 3 int findContentChildren(vector<int>& g, vector<int>& s) { 4 5 sort(g.begin(), g.end(), greater<int>()); 6 sort(s.begin(), s.end(), greater<int>()); 7 8 int si = 0 , gi = 0 ; 9 int res = 0 ; 10 while( gi < g.size() && si < s.size() ){ 11 12 if( s[si] >= g[gi] ){ 13 res ++ ; 14 si ++ ; 15 gi ++ ; 16 } 17 else 18 gi ++; 19 } 20 return res; 21 } 22 };
相关
- 392 Is Subsequence