leetcode:455. 分发饼干(贪心)

链接:https://leetcode-cn.com/problems/assign-cookies/
思路很简单,用尽量小的饼干去满足需求小的孩子即可。先排序,然后同时便利两个数组。
C++代码:

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        int result = 0;
        for(int i = 0,j = 0;;) 
        {
            if(i == g.size()||j == s.size())
                break;
            else if(s[j]>=g[i])
            {
                   i++;
                   j++;
                   result++; 
            }
            else if(s[j]<g[i])
            {
                j++;
            }
        }
        return result;  
    }
};

你可能感兴趣的:(leetcode)