LeetCode 455. 分发饼干

题目描述

455. 分发饼干

思路分析

解法一:排序 + 双指针(推荐)

核心思路

  • 将孩子的胃口值和饼干尺寸分别排序。
  • 用双指针从最小开始匹配,能满足就计数并移动两者。
  • 无法满足时只移动饼干指针,寻找更大的饼干。


复杂度分析

  • 时间复杂度:O(n log n),其中 n 表示数组长度。
  • 空间复杂度:O(1),排序额外空间不计入。
import java.util.Arrays;

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);

        int i = 0;
        int j = 0;
        int count = 0;

        while (i < g.length && j < s.length) {
            if (s[j] >= g[i]) {
                count++;
                i++;
                j++;
            } else {
                j++;
            }
        }

        return count;
    }
}
import "sort"

func findContentChildren(g []int, s []int) int {
	sort.Ints(g)
	sort.Ints(s)

	i, j := 0, 0
	count := 0

	for i < len(g) && j < len(s) {
		if s[j] >= g[i] {
			count++
			i++
			j++
		} else {
			j++
		}
	}

	return count
}

相似题目

题目 难度 考察点
135. 分发糖果 困难 贪心
860. 柠檬水找零 简单 贪心
881. 救生艇 中等 贪心
406. 根据身高重建队列 中等 贪心
1029. 两地调度 中等 贪心
本文作者:
本文链接: https://hgnulb.github.io/blog/2026/23924940
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!