zoukankan      html  css  js  c++  java
  • 力扣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;
        }
  • 相关阅读:
    cent os 6.8 php 5.6 安装ffmpeg扩展
    Linux查找目录下文件包含关键字
    python生成随机验证码
    zabbix添加任务计划和sshd文件修改key
    OS模块
    python模块
    python内建函数
    python3 爬煎蛋ooxx妹子图
    ssm整合-Sping整合Mybatis框架配置事务07
    ssm整合-Sping整合Mybatis框架06
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15426739.html
Copyright © 2011-2022 走看看