• 力扣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;
        }
  • 相关阅读:
    推销员问题
    string类实现
    链表倒数第k个节点
    设计模式之单例模式大全
    空类 sizeof 为什么是1
    类的三种继承方式
    单例模式典型创建方法(三种)
    虚函数实现
    链表删除结点
    TCP的状态转移
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15426739.html
Copyright © 2020-2023  润新知