代码随想录--贪心--分饼干

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。

对每个孩子 i,都有一个胃口值 gi,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 sj 。如果 sj >= gi,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

示例 1:

  • 输入: g = 1,2, s = 1,2,3
  • 输出: 2
  • 解释:你有两个孩子和三块小饼干,2 个孩子的胃口值分别是 1,2。你拥有的饼干数量和尺寸都足以让所有孩子满足。所以你应该输出 2.
java 复制代码
import java.util.Arrays;

public class Cookie {
    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; index--) {
            if(start >= 0 && g[index] <= s[start]) {
                start--;
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        //g = [1,2,3], s = [1,1]
        int[] g = {1,2};
        int[] s = {1,2,3};

        Cookie cookie = new Cookie();
        int res = cookie.findContentChildren(g, s);
        System.out.println(res);
    }
}
相关推荐
Frostnova丶7 小时前
【算法笔记】数学知识
笔记·算法
吴可可1237 小时前
AutoCAD 2016与2014二次开发关键差异
算法
雨白8 小时前
哈希:以时间换空间的算法实战
算法
啦啦啦啦啦zzzz9 小时前
数据结构:红黑树理论
数据结构·c++·红黑树
San813_LDD10 小时前
[数据结构]LeetCode学习
数据结构·算法·图论
x1387028595710 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta199811 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油11 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero12 小时前
Guava Cache Deep Dive
java·后端·算法·guava