455. Assign Cookies Greedy 贪心法

分饼干:因为饼干大小和孩子的食欲度不一定是按大小顺序排列的,所以开始要排序一下,然后从最小的饼干依次从食欲小的孩子开始看,如果他愿意吃,就++,看下一个小孩子,这回拿的就是大一点的饼干了。

Example 1:

Input: [1,2,3], [1,1]

Output: 1

Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int i=0,j=0,num=0;
        for(i = 0;i<s.length;i++){
            
                if(s[i]>=g[j]) {
                    num++;
                    if(j<g.length-1) {j++ ;}else break;
                }
            
        }
        
        return num;
    }
}

 

posted @ 2019-04-28 17:06  星之眷属  阅读(104)  评论(0编辑  收藏  举报