【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;
}

猜你喜欢

转载自blog.csdn.net/xqh_Jolene/article/details/124819923
今日推荐