题目描述

题目描述

解法

  • 贪心算法
    • 贪心策略:为了尽可能满足最多数量的孩子,从贪心的角度考虑,应该按照孩子的胃口从小到大的顺序依次满足每个孩子,且对于每个孩子,应该选择可以满足这个孩子的胃口且尺寸最小的饼干
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int findContentChildren(int[] g, int[] s) {
int child=0;
int cookies=0;
Arrays.sort(g);
Arrays.sort(s);
//先对两个数组进行排序
while (child<g.length&&cookies<s.length){
if(g[child]<=s[cookies]){
child++;
}
cookies++;
//因为本题要求每个人只能拿一个所以小饼干对于后边的孩子没有用,直接扔掉
}
return child;
}
}
  • 时间复杂度:O(m \log m + n \log n)为俩数组排序时间

链接:455. 分发饼干 - 力扣(LeetCode) (leetcode-cn.com)
来源:力扣(LeetCode)