455. 分发饼干『简单』

题目来源于力扣(LeetCode

一、题目

455. 分发饼干

题目相关标签:贪心算法

二、解题思路

  1. 对两个数组进行元素从小到大的排序,因为分发饼干时,胃口小的也可以分到较大的饼干,而胃口大的则需要更大的饼干

    即胃口值数组和饼干数组的元素都是非递减排序

  2. 所以采用贪心算法的思想,首先寻找是否有与胃口大小一致的饼干

  3. 当饼干值不存在与胃口值相等时,在饼干有序数组的基础上,索引右移找更大的元素

  4. 找到即满足一个胃口元素的饼干分发,count 值加 1

  5. 当前胃口值在饼干数组中遍历到最后仍然没有可以分发的饼干大小时,说明饼干数组中的元素都过小

  6. 无法满足当前胃口值的大小,更无法满足当前胃口值后的更大胃口值了,结束循环。

三、代码实现

public static int findContentChildren(int[] g, int[] s) {
    // 排除特殊情况
    if (g.length == 0 || s.length == 0) {
        return 0;
    }
    // 使孩子胃口有序,从小到大
    Arrays.sort(g);
    // 使饼干大小有序,从小到大
    Arrays.sort(s);
    // 记录能够满足的个数
    int count = 0;

    int i = 0;
    int j = 0;
    int glen = g.length;
    int slen = s.length;
    // 遍历两个数组
    while (i < glen && j < slen) {
        // 小于等于时,说明能满足
        if (g[i] <= s[j]) {
            count += 1;
            i++;
            j++;
        } else {
            // 因为数组是有序的,所以将索引 j 后移,寻找是否存在大于胃口值的饼干
            // 且寻找到的大于胃口值的饼干一定是大于的最小饼干
            j++;
        }
    }
    return count;
}

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    int[] g = {1, 2, 3}, s = {1, 1};  // output:1
//    int[] g = {1, 2}, s = {1, 2, 3};  // output:1
    int result = findContentChildren(g, s);
    System.out.println(result);
}
posted @ 2020-05-21 22:19  知音12138  阅读(196)  评论(0编辑  收藏  举报