455. 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.

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

问题解决:

对小孩要求数组和饼干大小进行排序,对于每个小孩分别对饼干大小数组进行遍历,找到第一个比要求大的饼干,若找到,同时把这个小孩和饼干从原数组删除,满足加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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值