Skip to content
本页目录

0455-分发饼干

https://leetcode.cn/problems/assign-cookies

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

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

示例 1:

输入: g = [1,2,3], s = [1,1]
输出: 1
解释: 
你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
所以你应该输出1。

示例 2:

输入: g = [1,2], s = [1,2,3]
输出: 2
解释: 
你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
你拥有的饼干数量和尺寸都足以让所有孩子满足。
所以你应该输出2.

提示:

  • 1 <= g.length <= 3 * 104
  • 0 <= s.length <= 3 * 104
  • 1 <= g[i], s[j] <= 231 - 1

思路1: 遍历孩子

遍历孩子的胃口,然后从饼干中找出符合条件的最小一块饼干分给他,并且将当前饼干置0,然后增加分配的饼干数。
为了减少查询,可以将饼干先排序,然后设置开始指针。

参考代码

csharp
public class Solution {
    public int FindContentChildren(int[] g, int[] s) {
    	//从小到大排列饼干
    	Array.Sort(s);
    	//从小到大排列孩子的胃口
    	Array.Sort(g);
    	int cookieIndex = 0;
    	int cookieAssignCount = 0;
    	for(int i=0; i<g.Length; i++){
    		while(cookieIndex < s.Length){
    			if(s[cookieIndex] >= g[i]){
    				cookieAssignCount++;
    				cookieIndex++;
    				break;
    			}
    			cookieIndex++;
    		}
    	}
    	return cookieAssignCount;
    }
}

思路2:遍历糖果

遍历糖果,当发现孩子胃口满足的时候,index++

csharp
public class Solution {
    public int FindContentChildren(int[] g, int[] s) {
    	//从小到大排列饼干
    	Array.Sort(s);
    	//从小到大排列孩子的胃口
    	Array.Sort(g);
    	int index = 0;
    	for(int i=0; i<s.Length; i++){
    		if(index < g.Length && g[index] <= s[i]){
    			index++;
    		}
    	}
    	return index;
  	}
}

复习:20220513

csharp
public class Solution {
    public int FindContentChildren(int[] g, int[] s) {
        //先从小到大排序
        Array.Sort(g);
        Array.Sort(s);
        int gIndex = 0;
        for(int i=0; i<s.Length; i++){
            if(gIndex < g.Length && g[gIndex] <= s[i]){
                gIndex++;
            }
        }
        return gIndex;
    }
}

Released under the MIT License.