204.贪心算法:分发饼干(力扣)

以下来源于代码随想录

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 result = 0;  // 记录满足的孩子数量
        
        // 从最大的胃口孩子开始检查
        for (int i = g.size() - 1; i >= 0; i--) 
        {
            // 如果当前饼干能够满足当前孩子
            if (index >= 0 && s[index] >= g[i]) 
            {
                index--;  // 使用这块饼干
                result++;  // 满足的孩子数量增加
            }
        }
        
        return result;  // 返回满足的孩子数量
    }
};
相关推荐
Frostnova丶5 小时前
【算法笔记】数学知识
笔记·算法
吴可可1236 小时前
AutoCAD 2016与2014二次开发关键差异
算法
雨白7 小时前
哈希:以时间换空间的算法实战
算法
San813_LDD9 小时前
[数据结构]LeetCode学习
数据结构·算法·图论
x138702859579 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta199810 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油10 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero11 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称11 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划