题目描述
有一群孩子和一堆饼干,每个孩子有一个饥饿度,每个饼干都有一个大小。每个孩子只能吃
最多一个饼干,且只有饼干的大小大于孩子的饥饿度时,这个孩子才能吃饱。求解最多有多少孩
子可以吃饱。
输入输出样例
输入两个数组,分别代表孩子的饥饿度和饼干的大小。输出最多有多少孩子可以吃饱的数
量。
Input: [1,2], [1,2,3]
Output: 2
//将两个数组进行排序,然后从饥饿度最小的孩子和大小最小的饼干开始对比,最后返回满足条件的个数(贪心算法)
static int findContentChildren(int[] g, int[] s) {
int temp;
for(int i = 0; i < g.length; i++){
for(int j = 0; j < g.length-i-1; j++){
if(g[j] > g[j+1]){
temp = g[j];
g[j] = g[j+1];
g[j+1] = temp;
}
}
}
for(int i = 0; i < s.length; i++){
for(int j = 0; j < s.length-i-1; j++){
if(s[j] > s[j+1]){
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
int child = 0, cookie = 0;
while(child < g.length && cookie < s.length){
System.out.println(g[child] + " " + s[cookie]);
if(g[child] <= s[cookie]){
child++;
cookie++;
}
else
cookie++;
}
return child;
}