455. Assign Cookies[easy]

455. Assign Cookies-Assignment Problem

Problem Description

Suppose you are a great parent and want to give your children some biscuits. However, each child can only give one cookie at most.

For each child i, there is an appetite value g[i], which is the smallest size of biscuit that can satisfy the appetite of the children; and each biscuit j has a size s[j]. If s[j] >= g[i], we can assign this cookie j to child i, and this child will be satisfied. Your goal is to satisfy as many children as possible and output this maximum value.

Example 1:

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

Example 2:

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

prompt:

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

answer

So that the child with the smallest appetite is the first to be satisfied, we should allocate biscuits that are greater than or equal to the child’s appetite and as small as possible to the child.
Ideas:
1. Sort the biscuits and children from small to large
. 2. Loop traversal. When the appetite "= the size of the cookie, it is a local optimal solution to this problem.
3. At the end of the loop, calculate the number of children satisfying the cycle condition (the number of children in the loop) Or any one of the cookies is gone)

Code

class Solution {
    
    
    public int findContentChildren(int[] g, int[] s) {
    
    
        //贪心问题
        // 尽可能满足较多数量的孩子
        //子问题 :每次让胃口小的孩子先满足  找到能够让胃口小孩子满足的最小的饼干
        //从小到大排序
        Arrays.sort(g);
        Arrays.sort(s);
        //双指针
        int child=0;
        int cookie=0;
        while(child < g.length && cookie <s.length ){
    
    
            if(s[cookie] >= g[child]){
    
    
                ++child;
            }
            //cookie 总要后移
            ++cookie;
        }
        return child;
    }
}

Guess you like

Origin blog.csdn.net/qq_37747189/article/details/115047517