From 11581df17788327ea3114c1f98d332af2cd0d260 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sun, 28 May 2023 17:58:11 -0500 Subject: [PATCH] =?UTF-8?q?Update=200455.=E5=88=86=E5=8F=91=E9=A5=BC?= =?UTF-8?q?=E5=B9=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0455.分发饼干.md | 43 ++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index efadb433..f32af57b 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -177,32 +177,33 @@ class Solution { ``` ### Python - +贪心 大饼干优先 ```python class Solution: - # 思路1:优先考虑小胃口 - def findContentChildren(self, g: List[int], s: List[int]) -> int: - g.sort() - s.sort() - res = 0 - for i in range(len(s)): - if res = g[res]: #小饼干先喂饱小胃口 - res += 1 - return res + 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: - # 思路2:优先考虑大胃口 - def findContentChildren(self, g: List[int], s: List[int]) -> int: - g.sort() - s.sort() - start, count = len(s) - 1, 0 - for index in range(len(g) - 1, -1, -1): # 先喂饱大胃口 - if start >= 0 and g[index] <= s[start]: - start -= 1 - count += 1 - return count + 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 # 返回满足的孩子数目 + ``` ### Go