阳泉网站设计推广网站有效的方法
关联LeetCode题号455
本题特点
- 贪心算法
- 通过局部解,推导出最优解,并且没有反例
本题思路
- 先排序很重要,因为这样就知道,已经使用过的饼干 肯定是不满足小朋友的胃口的
class Solution:def findContentChildren(self, g: List[int], s: List[int]) -> int:g.sort()s.sort()start, count = len(s) - 1, 0for index in range(len(g) - 1, -1, -1): # 先喂饱大胃口if start >= 0 and g[index] <= s[start]: start -= 1count += 1return count
# 使用两个变量 一重循环 控制两个数组的值的比较
两年后的想法:先满足最小的胃口
双循环不可以:是因为一块饼干给了一个人 就不能给第二个人,一个人也不能吃两块饼干
想用一个变量控制两个数组 不可以:饼干和孩子两个数组循环变化的节奏不一致
class Solution:def findContentChildren(self, g: List[int], s: List[int]) -> int:count = 0g.sort()s.sort()i = 0j = 0while i <= len(g)-1 and j <= len(s) -1:if g[i] <= s[j]:count += 1i += 1j += 1else:j += 1return count