【LeetCode】 455 Assign Cookies

it2023-09-19  63

题目描述

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 g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], 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.

 

Example 1:

Input: g = [1,2,3], s = [1,1]Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.  And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1.

 

Example 2:

Input: g = [1,2], s = [1,2,3]Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.  You have 3 cookies and their sizes are big enough to gratify all of the children,  You need to output 2.

 

Constraints:

1 <= g.length <= 3 * 1040 <= s.length <= 3 * 1041 <= g[i], s[j] <= 231 - 1

 

 

解题思路

基础贪心。

题意为有m个饼干每个饼干大小为s[i],有n个孩子每个孩子有一个贪婪因数为g[j]。给孩子们发饼干,第j个孩子只接受s[i]>=g[j]的饼干i,若得到符合条件的饼干,孩子得到满足。给定s[]和g[],求出能满足孩子的最大数量。

本题用贪心思想解决,即每次给当前满足因数最小的孩子他所能满足的最小的饼干。

详细点展开一步。将饼干按大小由小到大分发,对于每个饼干s[i],如果存在能以其满足的孩子,则发给能够满足的满足因数g[j]最小的孩子,如果不存在能以其满足的孩子,则说明这块饼干太小不能满足任何孩子,指针i后移到下一个饼干s[i+1],执行重复操作,直到遍历完成所有饼干。

再详细点展开一步。将饼干按大小由小到大分发,对于每个饼干s[i],按顺序与同为升序排列的孩子贪婪因数数组各项g[j]对比,找到满足s[i]>=g[j]的第一个j,将第i个饼干发给第j个孩子,计数后使饼干指针和孩子指针都后移判断下一个饼干i+1和孩子j+1,如果并没有g[j]满足s[i]>=g[j],则说明当前饼干无法满足任何一个孩子,使饼干指针后移判断下一个饼干i+1,直到遍历完成所有饼干。

 

 

提交代码

class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { int i=0, j=0, cnt=0; sort(g.begin(), g.end()); sort(s.begin(), s.end()); while(i<s.size()) { if(s[i]>=g[j]) { cnt++; i++; j++; if(j==g.size()) break; } else { i++; } } return cnt; } };

 

最新回复(0)