【Leetcode刷题笔记】455. 分发饼干

455. 分发饼干

题目描述

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。

对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

输入输出

Input: [1,2], [1,2,3]
Output: 2

题解

给当前剩余孩子里,饥饿度最小的孩子分配最小的能够饱腹的饼干。

先将两个数组排序,利用algorithm库中的sort函数,然后以孩子的饥饿感为主,从低到高分配饼干。

用到了sort函数

代码

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int child=0;
        int cookie=0;
        while (child<g.size()&&cookie<s.size()){
            if (g[child]<=s[cookie])
                child++;
            cookie++;
        }
        return child;
    }
};

int main() {
    Solution solution;
    vector<int> g;
    vector<int> s;
    int temp;
    while (cin >> temp) {
        g.push_back(temp);
        if (cin.get() == '\n')
            break;
    }
    while (cin >> temp) {
        s.push_back(temp);
        if (cin.get() == '\n')
            break;
    }
    int res = solution.findContentChildren(g, s);
    cout << res;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值