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;
        }
  • 相关阅读:
    Golang的类型转换实战案例
    Golang的基础数据类型-布尔型
    Golang的运算符优先级实操案例
    Golang的单目(一元)运算符-地址操作符和接收操作符
    基于Ambari的WebUI部署kafka服务
    HBase集群优化篇
    HBase Master的高可用实战案例
    HBase 数据迁移实战案例
    HBase API实战案例
    MySQL数据源接入DBus
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15426739.html
Copyright © 2011-2022 走看看