[Leetcode Brushing Notes] 455. Distributing Cookies

455. Distributing cookies

topic description

Let's say you're a great parent and want to give your kids some cookies. However, each child is given no more than one cookie.

For each child i, there is an appetite value g[i], which is the smallest size of biscuit that satisfies the child's appetite; and each biscuit j has a size s[j]. If s[j] >= g[i], we can assign this cookie j to child i, and this child will be satisfied. Your goal is to satisfy as many children as possible and output this maximum value.

input Output

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

answer

Among the currently remaining children, the child with the least hunger is allocated the smallest full biscuit.

First sort the two arrays, use the sort function in the algorithm library, and then distribute the biscuits from low to high based on the child's hunger.

The sort function is used

the code

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

Guess you like

Origin blog.csdn.net/xqh_Jolene/article/details/124819923