[One Question of the Day] Likou 455: Distribute Cookies

Title description ( portal )

Suppose you are a great parent and want to give your children some cookies. 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

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.

Ideas

Sort the two arrays, starting from the smallest, and his requirement is to ask all children as much as possible. We start from the smallest appetite value and traverse the cookie size from the smallest. If it is satisfied, directly num++, otherwise the s array will go back. The g array does not move, and the result of the loop is the largest num possible.

Code

 public int findContentChildren(int[] g, int[] s) {
    
    
        Arrays.sort(g);//胃口
        Arrays.sort(s);//饼干大小
        int num = 0;
        for (int i = 0,j=0; i < s.length && j < g.length; i++) {
    
    
            if (g[j] <= s[i]) {
    
    
                num++;
                j++;
            }
        }
        return num;
    }

Guess you like

Origin blog.csdn.net/weixin_45532227/article/details/111674022