LeetCode. 455 Distribute cookies (simple)

topic

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 gi, which is the smallest size of biscuit that can satisfy the appetite of the children; and each biscuit j has a size sj. If sj >= giwe can assign this cookie j to child i, the child will be satisfied. Your goal is to satisfy as many children as possible and output this maximum value.

note:

You can assume that the appetite value is positive.
A child can only have one cookie at most.

Example 1:

输入: [1,2,3], [1,1]

输出: 1

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

Example 2:

输入: [1,2], [1,2,3]

输出: 2

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

English station most votes

  • Here’s a slightly more readable version: greedy java simple
public class Solution {
    
    
    public int findContentChildren(int[] children, int[] cookies) {
    
    
        Arrays.sort(children);
        Arrays.sort(cookies);
        
        int child = 0;
        for (int cookie = 0; child < children.length && cookie < cookies.length; cookie ++) {
    
    
            if (cookies[cookie] >= children[child]) {
    
    
                child ++;
            }
        }
        
        return child;
    }
}

Simplified version of the code above

public class Solution {
    
    
    public int findContentChildren(int[] g, int[] s) {
    
    
		Arrays.sort(g);
		Arrays.sort(s);
		int i = 0;
		for(int j=0;i<g.length && j<s.length;j++) {
    
    
			if(g[i]<=s[j]) i++;
		}
		return i;
    }
}    

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106941542