LeetCode 455 Assign Cookies 分配饼干(贪心)

思路:第一个数组是每个孩子需要的饼干大小(可以这么理解吧,贪婪因子),第二个数组是每个饼干饼干的实际大小

问:有 几个孩子能拿到饼干得到满足 

要求:每个孩子最多一块饼干(也就是说不能多块凑够满足他)

那么最简单的思路就是把两个数组排序,然后比较两个数组的开头,能满足,count++,不能满足,扔掉没用的饼干,看下一个饼干能不能满足孩子

java代码

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int i=0,j=0;
        int count=0;
        while(i< g.length && j<s.length){
            if(g[i]<=s[j]){
                i++;
                j++;
                count++;
            }
            else{
                j++;
            }
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/yysave/article/details/84074894