贪心算法简单来说就是选择目前最短最优的选项,比如LeetCode455的分发饼干,这里我们可以先把大饼干给大胃口的孩子吃,然后小饼干再给小胃口的孩子吃
代码如下:
//g是孩子的胃口数组,s是拥有的饼干数组
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int start = s.length - 1;
// 遍历孩子的胃口
for (int index = g.length - 1; index >= 0; index--) {
if(start >= 0 && g[index] <= s[start]) {
start--;
count++;
}
}
return count;
}