参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们受益!

# 455.分发饼干 [力扣题目链接](https://leetcode.cn/problems/assign-cookies/) 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 对每个孩子 i,都有一个胃口值  g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 示例  1: - 输入: g = [1,2,3], s = [1,1] - 输出: 1 解释:你有三个孩子和两块小饼干,3 个孩子的胃口值分别是:1,2,3。虽然你有两块小饼干,由于他们的尺寸都是 1,你只能让胃口值是 1 的孩子满足。所以你应该输出 1。 示例  2: - 输入: g = [1,2], s = [1,2,3] - 输出: 2 - 解释:你有两个孩子和三块小饼干,2 个孩子的胃口值分别是 1,2。你拥有的饼干数量和尺寸都足以让所有孩子满足。所以你应该输出 2. 提示: - 1 <= g.length <= 3 \* 10^4 - 0 <= s.length <= 3 \* 10^4 - 1 <= g[i], s[j] <= 2^31 - 1 ## 算法公开课 **[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[贪心算法,你想先喂哪个小孩?| LeetCode:455.分发饼干](https://www.bilibili.com/video/BV1MM411b7cq),相信结合视频在看本篇题解,更有助于大家对本题的理解**。 ## 思路 为了满足更多的小孩,就不要造成饼干尺寸的浪费。 大尺寸的饼干既可以满足胃口大的孩子也可以满足胃口小的孩子,那么就应该优先满足胃口大的。 **这里的局部最优就是大饼干喂给胃口大的,充分利用饼干尺寸喂饱一个,全局最优就是喂饱尽可能多的小孩**。 可以尝试使用贪心策略,先将饼干数组和小孩数组排序。 然后从后向前遍历小孩数组,用大饼干优先满足胃口大的,并统计满足小孩数量。 如图: ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230405225628.png) 这个例子可以看出饼干 9 只有喂给胃口为 7 的小孩,这样才是整体最优解,并想不出反例,那么就可以撸代码了。 C++代码整体如下: ```CPP // 版本一 class Solution { public: int findContentChildren(vector& g, vector& 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]) { // 遍历饼干 result++; index--; } } return result; } }; ``` * 时间复杂度:O(nlogn) * 空间复杂度:O(1) 从代码中可以看出我用了一个 index 来控制饼干数组的遍历,遍历饼干并没有再起一个 for 循环,而是采用自减的方式,这也是常用的技巧。 有的同学看到要遍历两个数组,就想到用两个 for 循环,那样逻辑其实就复杂了。 ### 注意事项 注意版本一的代码中,可以看出来,是先遍历的胃口,在遍历的饼干,那么可不可以 先遍历 饼干,在遍历胃口呢? 其实是不可以的。 外面的 for 是里的下标 i 是固定移动的,而 if 里面的下标 index 是符合条件才移动的。 如果 for 控制的是饼干, if 控制胃口,就是出现如下情况 : ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230112102848.png) if 里的 index 指向 胃口 10, for 里的 i 指向饼干 9,因为 饼干 9 满足不了 胃口 10,所以 i 持续向前移动,而 index 走不到` s[index] >= g[i]` 的逻辑,所以 index 不会移动,那么当 i 持续向前移动,最后所有的饼干都匹配不上。 所以 一定要 for 控制 胃口,里面的 if 控制饼干。 ### 其他思路 **也可以换一个思路,小饼干先喂饱小胃口** 代码如下: ```CPP class Solution { public: int findContentChildren(vector& g, vector& s) { sort(g.begin(),g.end()); sort(s.begin(),s.end()); int index = 0; for(int i = 0; i < s.size(); i++) { // 饼干 if(index < g.size() && g[index] <= s[i]){ // 胃口 index++; } } return index; } }; ``` * 时间复杂度:O(nlogn) * 空间复杂度:O(1) 细心的录友可以发现,这种写法,两个循环的顺序改变了,先遍历的饼干,在遍历的胃口,这是因为遍历顺序变了,我们是从小到大遍历。 理由在上面 “注意事项”中 已经讲过。 ## 总结 这道题是贪心很好的一道入门题目,思路还是比较容易想到的。 文中详细介绍了思考的过程,**想清楚局部最优,想清楚全局最优,感觉局部最优是可以推出全局最优,并想不出反例,那么就试一试贪心**。 ## 其他语言版本 ### Java ```java class Solution { // 思路1:优先考虑饼干,小饼干先喂饱小胃口 public int findContentChildren(int[] g, int[] s) { Arrays.sort(g); Arrays.sort(s); int start = 0; int count = 0; for (int i = 0; i < s.length && start < g.length; i++) { if (s[i] >= g[start]) { start++; count++; } } return count; } } ``` ```java class Solution { // 思路2:优先考虑胃口,先喂饱大胃口 public int findContentChildren(int[] g, int[] s) { Arrays.sort(g); Arrays.sort(s); int count = 0; int start = s.length - 1; // 遍历胃口 for (int index = g.length - 1; index >= 0; index--) { if(start >= 0 && g[index] <= s[start]) { start--; count++; } } return count; } } ``` ### Python 贪心 大饼干优先 ```python class Solution: def findContentChildren(self, g, s): g.sort() # 将孩子的贪心因子排序 s.sort() # 将饼干的尺寸排序 index = len(s) - 1 # 饼干数组的下标,从最后一个饼干开始 result = 0 # 满足孩子的数量 for i in range(len(g)-1, -1, -1): # 遍历胃口,从最后一个孩子开始 if index >= 0 and s[index] >= g[i]: # 遍历饼干 result += 1 index -= 1 return result ``` 贪心 小饼干优先 ```python class Solution: def findContentChildren(self, g, s): g.sort() # 将孩子的贪心因子排序 s.sort() # 将饼干的尺寸排序 index = 0 for i in range(len(s)): # 遍历饼干 if index < len(g) and g[index] <= s[i]: # 如果当前孩子的贪心因子小于等于当前饼干尺寸 index += 1 # 满足一个孩子,指向下一个孩子 return index # 返回满足的孩子数目 ``` 栈 大饼干优先 ```python from collecion import deque class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: #思路,饼干和孩子按从大到小排序,依次从栈中取出,若满足条件result += 1 否则将饼干栈顶元素重新返回 result = 0 queue_g = deque(sorted(g, reverse = True)) queue_s = deque(sorted(s, reverse = True)) while queue_g and queue_s: child = queue_g.popleft() cookies = queue_s.popleft() if child <= cookies: result += 1 else: queue_s.appendleft(cookies) return result ``` ### Go 版本一 大饼干优先 ```Go func findContentChildren(g []int, s []int) int { sort.Ints(g) sort.Ints(s) index := len(s) - 1 result := 0 for i := len(g) - 1; i >= 0; i-- { if index >= 0 && s[index] >= g[i] { result++ index-- } } return result } ``` 版本二 小饼干优先 ```Go func findContentChildren(g []int, s []int) int { sort.Ints(g) sort.Ints(s) index := 0 for i := 0; i < len(s); i++ { if index < len(g) && g[index] <= s[i] { index++ } } return index } ``` ### Rust ```rust pub fn find_content_children(mut children: Vec, mut cookies: Vec) -> i32 { children.sort(); cookies.sort(); let (mut child, mut cookie) = (0, 0); while child < children.len() && cookie < cookies.len() { // 优先选择最小饼干喂饱孩子 if children[child] <= cookies[cookie] { child += 1; } cookie += 1; } child as i32 } ``` ### Javascript ```js var findContentChildren = function (g, s) { g = g.sort((a, b) => a - b); s = s.sort((a, b) => a - b); let result = 0; let index = s.length - 1; for (let i = g.length - 1; i >= 0; i--) { if (index >= 0 && s[index] >= g[i]) { result++; index--; } } return result; }; ``` ### TypeScript ```typescript // 大饼干尽量喂胃口大的 function findContentChildren(g: number[], s: number[]): number { g.sort((a, b) => a - b); s.sort((a, b) => a - b); const childLength: number = g.length, cookieLength: number = s.length; let curChild: number = childLength - 1, curCookie: number = cookieLength - 1; let resCount: number = 0; while (curChild >= 0 && curCookie >= 0) { if (g[curChild] <= s[curCookie]) { curCookie--; resCount++; } curChild--; } return resCount; } ``` ```typescript // 小饼干先喂饱小胃口的 function findContentChildren(g: number[], s: number[]): number { g.sort((a, b) => a - b); s.sort((a, b) => a - b); const childLength: number = g.length, cookieLength: number = s.length; let curChild: number = 0, curCookie: number = 0; while (curChild < childLength && curCookie < cookieLength) { if (g[curChild] <= s[curCookie]) { curChild++; } curCookie++; } return curChild; } ``` ### C ```c ///小餅乾先餵飽小胃口的 int cmp(int* a, int* b) { return *a - *b; } int findContentChildren(int* g, int gSize, int* s, int sSize){ if(sSize == 0) return 0; //将两个数组排序为升序 qsort(g, gSize, sizeof(int), cmp); qsort(s, sSize, sizeof(int), cmp); int numFedChildren = 0; int i = 0; for(i = 0; i < sSize; ++i) { if(numFedChildren < gSize && g[numFedChildren] <= s[i]) numFedChildren++; } return numFedChildren; } ``` ```c ///大餅乾先餵飽大胃口的 int cmp(int* a, int* b) { return *a - *b; } int findContentChildren(int* g, int gSize, int* s, int sSize){ if(sSize == 0) return 0; //将两个数组排序为升序 qsort(g, gSize, sizeof(int), cmp); qsort(s, sSize, sizeof(int), cmp); int count = 0; int start = sSize - 1; for(int i = gSize - 1; i >= 0; i--) { if(start >= 0 && s[start] >= g[i] ) { start--; count++; } } return count; } ``` ### Scala ```scala object Solution { def findContentChildren(g: Array[Int], s: Array[Int]): Int = { var result = 0 var children = g.sorted var cookie = s.sorted // 遍历饼干 var j = 0 for (i <- cookie.indices) { if (j < children.size && cookie(i) >= children(j)) { j += 1 result += 1 } } result } } ``` ### C# ```csharp public class Solution { public int FindContentChildren(int[] g, int[] s) { Array.Sort(g); Array.Sort(s); int index = s.Length - 1; int res = 0; for (int i = g.Length - 1; i >=0; i--) { if(index >=0 && s[index]>=g[i]) { res++; index--; } } return res; } } ```