我实现的方法:
贪心算法
先将胃口glist和饼干大小slist按降序排列
每次,当slist非空时,从slist中pop出最大的一个饼干
每次,当glist非空时,从glist中pop出最大的一个胃口
如果当前饼干>=当前胃口
res +=1
break#换下一饼干
如果 当前饼干<当前胃口
continue#试下一个胃口
返回res
class Solution:
def findContentChildren(self, g, s):
if s == [] or g == []:
return 0
g = sorted(g, reverse = True)#[3,2,1]胃口
s = sorted(s, reverse = True)#[1,1]饼干大小
print(g,'胃口')
print(s,'饼干大小')
maxs = s[0]
tempvalue = 0
for i in range(len(g)):
if g[i] <= maxs:
tempvalue = i
break
g = g[i:]
if g == []:
return 0
res = 0
tempindex = 0
while s != []:#当饼干序列非空时,即还有饼干可测试时
values = s.pop(0)#获取当前最大的饼干大小
while g != []:#以下代码段中values不变
valueg = g.pop(0)#获取当前最大胃口
if valueg <= values:#胃口 <= 当前这块饼干的大小,即能满足这个孩子:
res += 1
break
elif valueg > values:#胃口 > 当前饼干大小:
continue
return res