leetcode 455 分发饼干
贪心法则,自己的做法,先将两个数组进行排序,然后遍历饼干列表,当前的饼干列表只能在已经满足了当前胃口了的,如果满足条件则数量增加1,然后当前胃口也继续检测下一个。
注意 如果是嵌套循环的话, break 可以跳出最深的循环,打破最小的循环。而continue是跳过当前循环的下面语句,继续循环,
break 跳出整个循环,continue 跳出当前循环。
看到题解中的这句话感觉很棒。
想清楚局部最优,想清楚全局最优,感觉局部最优是可以推出全局最优,并想不出反例,那么就试一试贪心。
class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: s=sorted(s) g=sorted(g) count=0 start=-1 end=float('inf') j=0 for i in range(len(s)): if g[j]<=s[i]: count+=1 if j<len(g)-1: j+=1 else: return count return count
也可以通过while 来进行遍历,双指针。
语言: python3 class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: s=sorted(s) g=sorted(g) count=0 i=0 j=0 while i<len(s) and j<len(g): if s[i]>=g[j]: count+=1 i+=1 j+=1 else: i+=1 return count