您的位置:首页 > 其它

LeetCode题解:Assign Cookies

2017-01-02 14:25 387 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: