Leetcode brushing record-455. Distribution of cookies

Insert picture description here

The method I implemented: the
greedy algorithm.
First sort the appetite glist and the cookie size slist in descending order.
Each time, when the slist is not empty, the largest cookie pops out from the slist.
Every time, when the glist is not empty, pop out from the glist. The biggest appetite
if the current biscuit> = current appetite
res + = 1
break # change the next biscuit
if the current biscuit <current appetite
continue # try the next appetite
return 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

Published 43 original articles · praised 14 · 20,000+ views

Guess you like

Origin blog.csdn.net/weixin_41545780/article/details/105047024