Easy to understand C++ using std::sort()

  • 0

    Sort the children's greed and cookie size in ascending order. Then see if the smallest cookie at position s[j] will satisfy the least greedy child at position g[i]. If that cookie does NOT satisfy this child, then that cookie will also NOT satisfy a more greedy child, so continue moving onto the next largest cookie until the least greedy child is satisfied. Then move onto the next least greedy child and repeat.

    class Solution{
        int findContentChildren(vector<int>& g, vector<int>& s){
            sort(g.begin(), g.end());
            sort(s.begin(), s.end());
            int res=0, j=0;
            for (int i=0; i < g.size(); i++){
                while (j < s.size() && g[i] > s[j]){ j++; }
                if (j < s.size()) { res++; j++; }
            return res;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.