问题描述:
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.
分析:题目很简单,说有大小不一的一些饼干,还有饥饿程度不同的孩子。我们需要把饼干分配给孩子,要求饼干大小>=孩子的需求,且一个孩子只能得到一块饼干。求出最多能分配多少饼干(亦即能让多少孩子吃饱)
思路:典型的贪心算法。我们先排序,再分配。分配时我们从需求最小的孩子开始,给予能满足他的最小块的饼干。如果最小的饼干可以满足需求最小的孩子,则我们排除这个孩子和这块饼干并增加一个记录;否则,我们要尝试用更大一点的饼干给这个孩子。循环直到饼干没了或孩子都拿到饼干了。
代码如下:
class Solution {
public int findContentChildren(int[] g, int[] s) {
//sort the two arrays
Arrays.sort(g);
Arrays.sort(s);
int i=0;
int j=0;
int counter=0;
//loop if we have cookies and hungry children
while((i<=g.length-1)&&(j<=s.length-1)){
//if we can feed the least greedy child with the smallest cookie
if(s[j]>=g[i]){
i++;
j++;
counter++;
}
//otherwise, we try to feed the least greedy child with a bigger cookie
else{
j++;
}
}
return counter;
}
}
时间复杂度: O(nlogn), 受制于排序算法