刷代码随想录有感(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;
    }
};

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

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

贪心算法没有套路。

相关推荐
阿豪学编程7 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
墨韵流芳8 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
csdn_aspnet8 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
凌波粒9 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
paeamecium10 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试
Book思议-10 小时前
【数据结构】栈与队列全方位对比 + C 语言完整实现
c语言·数据结构·算法··队列
SteveSenna10 小时前
项目:Trossen Arm MuJoCo
人工智能·学习·算法
NAGNIP10 小时前
一文搞懂CNN经典架构-DenseNet!
算法·面试
道法自然|~10 小时前
BugCTF黄道十二宫
算法·密码学
WHS-_-202211 小时前
Python 算法题学习笔记一
python·学习·算法