455. Assign Cookies

来源:互联网 发布:内蒙古大数据局局长 编辑:程序博客网 时间:2024/06/01 08:53

问题描述:

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.

给两个数组,一个代表小孩对饼干的大小要求,另一个代表饼干的大小,至多给小孩发一块饼干且小孩对饼干的大小要求总是正数。发的饼干大小必须大于或等于小孩对饼干的大小要求才能满足小孩。求至多能满足几个小孩。

问题解决:

对小孩要求数组和饼干大小进行排序,对于每个小孩分别对饼干大小数组进行遍历,找到第一个比要求大的饼干,若找到,同时把这个小孩和饼干从原数组删除,满足加1

代码如下:

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        //分别排序
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        //两个迭代器
        vector<int>::iterator iter1 = g.begin();
        vector<int>::iterator iter2 = s.begin();
        //计算满足数量
        int num = 0;
        //两层循环搜索小孩饼干
        for(int i = 0; i < g.size(); i++) {
            for(int j = 0; j < s.size(); j++) {
                vector<int>::iterator iter3 = iter1+i;
                vector<int>::iterator iter4 = iter2+j;
                //若找到第一个满足的饼干
                if(*iter3 <= *iter4) {
                    num++;
                    i--,j--;
                    g.erase(iter3);
                    s.erase(iter4);
                    break;
                }
            }
        }
        return num;
    }
};


原创粉丝点击