LeetCode455☞分发饼干

关联LeetCode题号455

本题特点
  • 贪心算法
  • 通过局部解,推导出最优解,并且没有反例
本题思路
  1. 先排序很重要,因为这样就知道,已经使用过的饼干 肯定是不满足小朋友的胃口的
python 复制代码
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        start, count = len(s) - 1, 0
        for index in range(len(g) - 1, -1, -1): # 先喂饱大胃口
            if start >= 0 and g[index] <= s[start]: 
                start -= 1
                count += 1
        return count
# 使用两个变量 一重循环 控制两个数组的值的比较

两年后的想法:先满足最小的胃口

双循环不可以:是因为一块饼干给了一个人 就不能给第二个人,一个人也不能吃两块饼干

想用一个变量控制两个数组 不可以:饼干和孩子两个数组循环变化的节奏不一致

java 复制代码
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        count = 0
        g.sort()
        s.sort()
        i = 0
        j = 0
        while i <= len(g)-1 and j <= len(s) -1:
            if g[i] <= s[j]:
                count += 1
                i += 1
                j += 1
            else:
                j += 1
        return count
相关推荐
ZhengEnCi3 小时前
M3-markconv库找不到wkhtmltopdf问题
python
2301_764441335 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI5 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly6 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives6 小时前
atcoder ABC 452 题解
数据结构·算法
chushiyunen6 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA6 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
feifeigo1236 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
baidu_huihui6 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳6 小时前
Python从入门到精通day63
开发语言·python