1. 程式人生 > >LeetCode題解:Assign Cookies

LeetCode題解:Assign Cookies

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Note:
You may assume the greed factor is always positive. 

You cannot assign more than one cookie to one child.

思路:

注意到一個小孩只能拿到最多一個餅乾。於是貪婪演算法可解。

題解:

int findContentChildren(std::vector<int>& g, std::vector<int>& s) {
    std::sort(std::begin(g), std::end(g));
    std::sort(std::begin(s), std::end(s));

    int count(0);
    size_t sIter(0);
    for(size_t i = 0; i < g.size(); ++i) {
        while(sIter < s.size() && g[i] > s[sIter]) ++sIter;
        if (sIter < s.size() && g[i] <= s[sIter]) {
            ++sIter; ++count;
        }
    }
    return count;
}