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
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 <len(g) and s[i] >= 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