mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 0455.分发饼干.md
This commit is contained in:
@ -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
|
||||||
|
Reference in New Issue
Block a user