刷代码随想录有感(81):贪心算法——分发饼干

题干:

cpp 复制代码
class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int index = s.size() - 1;
        int res = 0;
        for(int i = g.size() - 1; i >= 0; i--){
            if(index >= 0 && s[index] >= g[i]){
                res++;
                index--;
            }
        }
        return res;
    }
};

贪心算法------更多的是瞪眼法,通过局部最优推出整体最优。本题思路是把大饼干给胃口大的孩子

从大到小依次遍历孩子看是否对的上最大饼干,然后依次下降。

贪心算法没有套路。

相关推荐
田梓燊6 分钟前
leetcode 56
java·算法·leetcode
仍然.29 分钟前
多线程---阻塞队列收尾和线程池
java·开发语言·算法
_深海凉_29 分钟前
LeetCode热题100-最长公共前缀
算法·leetcode·职场和发展
郝学胜-神的一滴29 分钟前
PyTorch自动微分核心解析:从原理到实战实现权重更新
人工智能·pytorch·python·深度学习·算法·机器学习
会编程的土豆1 小时前
【数据结构与算法】 拓扑排序
数据结构·c++·算法
zth4130211 小时前
SegmentSplay‘s Super STL(v2.2)
开发语言·c++·算法
数据知道1 小时前
claw-code 源码详细分析:Bootstrap Graph——启动阶段图式化之后,排障与扩展为什么会变简单?
前端·算法·ai·bootstrap·claude code·claw code
Kel1 小时前
从Prompt到Response:大模型推理端到端核心链路深度拆解
人工智能·算法·架构
Felven1 小时前
D. Matryoshkas
算法
17(无规则自律)2 小时前
DFS连通域统计:岛屿数量问题及其变形
c++·算法·深度优先