Leetcode 455. 分发饼干 贪心

地址  https://leetcode-cn.com/problems/assign-cookies/

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

注意:

你可以假设胃口值为正。
一个小朋友最多只能拥有一块饼干。

示例 1:

输入: [1,2,3], [1,1]

输出: 1

解释: 
你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
所以你应该输出1。
示例 2:

输入: [1,2], [1,2,3]

输出: 2

解释: 
你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
你拥有的饼干数量和尺寸都足以让所有孩子满足。
所以你应该输出2.

解法 

孩子的需求和饼干都排序 尽量用最接近孩子的需求的饼干去满足需求

第一次的代码如下

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        int count  =0;
        for(int i= 0; i < g.size();i++){
            int need = g[i]; int find = 0;
            for(int j=0;j < s.size();j++){
                if(s[j]>= g[i]){
                    s[j] = -1;
                    count ++;
                    find = 1;
                    break;
                } 
            }
            if(find ==0) break;
            
        }
        
        return count ;
        
    }
};

但是实际上 第二重循环是可以优化的 不必每次都从最开始遍历 而是从上一次找到的饼干的索引处遍历

另外某一次无法找到匹配的饼干那么就可以提前离开了

写了两份代码 如下

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        int count  =0;
        
        int start = 0;
        
        for(int i = 0; i < g.size();i++){
            int need = g[i];int find = 0;
            for(int j = start;j < s.size();j++){
                if(s[j] >= g[i]){
                    count++;
                    start = j+1;
                    find =1;
                    break;
                }
            }
            if(find == 0) break;
            
        }
        
        
        return count ;
        
    }
};
class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        int i = 0;int j = 0;int res = 0;
        for(int i = 0; i < g.size();i++){
            while(j <s.size() && s[j] < g[i]) j++;
            if(j <s.size()){
                res++; j++;
            }
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/itdef/p/12824531.html