#leetCode刷题纪实 Day19
https://leetcode-cn.com/problems/assign-cookies/
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
注意:
你可以假设胃口值为正。
一个小朋友最多只能拥有一块饼干。
示例 1:
输入: [1,2,3], [1,1]
输出: 1
解释:
你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
所以你应该输出1。
示例 2:
输入: [1,2], [1,2,3]
输出: 2
解释:
你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
你拥有的饼干数量和尺寸都足以让所有孩子满足。
所以你应该输出2.
小菜鸡的尝试:
思路是我要先把我的小饼干分出去,把饼干从小到大分给胃口从小到大的孩子
于是想到了优先队列(但空间复杂度就很大,时间复杂度也不算小 O(3n)),不过能通过
1 class Solution { 2 public: 3 int findContentChildren(vector<int>& g, vector<int>& s) { 4 priority_queue<int, vector<int>, greater<int> > child; 5 priority_queue<int, vector<int>, greater<int> > me; 6 for (int i = 0; i < g.size(); i ++) { 7 child.push(g[i]); 8 } 9 for (int i = 0; i < s.size(); i ++) { 10 me.push(s[i]); 11 } 12 int count = 0; 13 while (!me.empty() && !child.empty()) { 14 cout << me.top() << child.top() << endl; 15 if (me.top() >= child.top()) { 16 count ++; 17 me.pop(); 18 child.pop(); 19 } else { 20 me.pop(); 21 } 22 } 23 return count; 24 } 25 };
膜拜大佬代码:
思路是一样的,但把优先队列的处理改成了sort函数,节约了时间和空间
1 class Solution { 2 public: 3 int findContentChildren(vector<int>& g, vector<int>& s) { 4 int ans = 0; 5 sort(g.begin(), g.end(), greater<int>()); 6 sort(s.begin(), s.end(), greater<int>()); 7 for (int i = 0; i < g.size() && ans < s.size(); i++) 8 if (g[i] <= s[ans]) 9 ans++; 10 return ans; 11 } 12 };
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/assign-cookies
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

浙公网安备 33010602011771号