题目:
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.
解析:
现将给出的两个数组(孩子满意度数组和糖果大小数组)进行排序,排好序后,设置两个点分别存在两个数组中(点作为数组特殊下标),当两个点分别小于两个数组的大小时,进行判定,若孩子满意度数组中的点对应的满意大小值比糖果大小数组中的点对应的大小值要更小,说明满足标准,两个点加加(即跳过这一对),若大于,则只将糖果大小数组的点加加,将下一个糖果大小值与原本不满足的孩子满意度大小值对比,直到有一个点超过其对应数组的大小值,则退出,输出孩子满意度大小值对应的点(即符合条件的点)。
代码:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int pg=0;
int ps=0;
while(pg<g.length() &&ps<s.length()){
if(g[pg]<=s[ps]){
ps++;
pg++;
}
else{
ps++;
}
}
return pg;
}
};