力扣455题(分发饼干)

455、分发饼干

基本思想:

贪心算法

具体实现:

A 优先考虑胃口,先喂饱大胃口

大尺寸的饼干既可以满足胃口大的孩子也可以满足胃口小的孩子,那么就应该优先满足胃口大的。

 

1.先将饼干数组和小孩数组排序

2.从后向前遍历小孩数组,用大饼干优先满足胃口大的,并统计满足小孩

 

B 优先考虑饼干,小饼干先喂饱小胃口

小胃口的孩子既可以吃大尺寸的饼干也可以吃小尺寸的饼干,那么就应该优先考虑小尺寸的饼干。

1.先将饼干数组和小孩数组排序

2.从前向后遍历饼干数组,用小饼干优先满足胃口小的,并统计吃掉的饼干数量

 

代码:

class Solution {
    // 思路A:优先考虑胃口,先喂饱大胃口
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int count = 0;
        int start = s.length - 1;
        // 遍历胃口
        for (int index = g.length - 1; index >= 0 && start >= 0; index--) {
            if( g[index] <= s[start]) {
                start--;
                count++;
            }
        }
        return count;
    }
}

 

class Solution {
    // 思路B:优先考虑饼干,小饼干先喂饱小胃口
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int start = 0;
        int count = 0;
        for (int i = 0; i < s.length && start < g.length; i++) {
            if (s[i] >= g[start]) {
                start++;
                count++;
            }
        }
        return count;
    }

 

posted @ 2021-10-19 22:10  最近饭吃的很多  阅读(55)  评论(0编辑  收藏  举报