Update 0455.分发饼干.md

This commit is contained in:
jianghongcheng
2023-05-28 17:58:11 -05:00
committed by GitHub
parent 93e0a18f0f
commit 11581df177

View File

@ -177,32 +177,33 @@ class Solution {
``` ```
### Python ### Python
贪心 大饼干优先
```python ```python
class Solution: class Solution:
# 思路1优先考虑小胃口 def findContentChildren(self, g, s):
def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() # 将孩子的贪心因子排序
g.sort() s.sort() # 将饼干的尺寸排序
s.sort() index = len(s) - 1 # 饼干数组的下标,从最后一个饼干开始
res = 0 result = 0 # 满足孩子的数量
for i in range(len(s)): for i in range(len(g)-1, -1, -1): # 遍历胃口,从最后一个孩子开始
if res <len(g) and s[i] >= g[res]: #小饼干先喂饱小胃口 if index >= 0 and s[index] >= g[i]: # 遍历饼干
res += 1 result += 1
return res index -= 1
return result
``` ```
贪心 小饼干优先
```python ```python
class Solution: class Solution:
# 思路2优先考虑大胃口 def findContentChildren(self, g, s):
def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() # 将孩子的贪心因子排序
g.sort() s.sort() # 将饼干的尺寸排序
s.sort() index = 0
start, count = len(s) - 1, 0 for i in range(len(s)): # 遍历饼干
for index in range(len(g) - 1, -1, -1): # 先喂饱大胃口 if index < len(g) and g[index] <= s[i]: # 如果当前孩子的贪心因子小于等于当前饼干尺寸
if start >= 0 and g[index] <= s[start]: index += 1 # 满足一个孩子,指向下一个孩子
start -= 1 return index # 返回满足的孩子数目
count += 1
return count
``` ```
### Go ### Go