有两个数组,一个用来存放每个孩子的满足度,一个用来存放每个饼干的大小,只有饼干大小>=孩子满足度,孩子才能满足,求能满足最多孩子数量。
import java.util.Arrays;
public class FindContentChildren {
public static int findContentChildren(int[] greed,int[] size){
Arrays.sort(greed);
Arrays.sort(size);
int g=0;//用于定位循环中greed数组下标,和统计满足孩子数量
int s=0;//定位size数组下标
while(g<greed.length&&s<size.length){
if(greed[g]<=size[s]){
g++;
}
s++;
}
return g;
}
public static void main(String[] args){
int[] arr1={1,3,5,7,3};//排序后13357
int[] arr2={2,5,8,1};//排序后1258
System.out.print(findContentChildren(arr1,arr2));//打印结果3
}
}
本文介绍了一种通过分配不同大小的饼干给具有不同满足度的孩子,以满足最多孩子的算法实现。该算法首先对孩子的满足度和饼干大小进行排序,然后采用贪心策略,每次尝试用最小的饼干满足当前最易满足的孩子,直至无法满足为止。
1272

被折叠的 条评论
为什么被折叠?



