[Java] 455. Distribute cookies-----Time complexity O(n) solves the problem! ! !

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:

Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation:
You have three children and two biscuits. The appetite values ​​of the three children are: 1, 2, 3.
Although you have two small biscuits, since their size is 1, you can only satisfy the child whose appetite is 1.
So you should output 1.
Example 2:

Input: g = [1,2], s = [1,2,3]
Output: 2
Explanation:
You have two children and three biscuits. The appetites of the two children are 1,2, respectively.
The number and size of biscuits you have are enough to satisfy all children.
So you should output 2.

prompt:

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

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

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/111660514