自己写的,没有使用排序 ,会超出时间限制:
class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: if len(s)==0: return 0 count=0 for i in range(len(g)): mydict = {} for j in range(len(s)): if s[j]==g[i]: s[j]=-100 count+=1 mydict={} break elif s[j]>g[i] : mydict.update({s[j]:j}) if len(mydict)!=0: min_key=min(mydict.keys()) s[mydict[min_key]]=-100 count += 1 return count
使用sort():
class Solution: def findContentChildren(self, children: List[int], cookies: List[int]) -> int: # 将孩子的胃口和饼干排序 children.sort() cookies.sort() # 孩子的数量 num_children = len(children) # 饼干的数量 num_cookies = len(cookies) # 记录结果 satisfied_children = 0 for i in range(num_cookies): # 从胃口小的孩子开始喂 if satisfied_children < num_children and children[satisfied_children] <= cookies[i]: satisfied_children += 1 return satisfied_children
标签:cookies,饼干,int,leedcode,len,num,mydict,children,贪心 From: https://www.cnblogs.com/yyyjw/p/18177289