链接:分发饼干
解法1:优先喂饱胃口大的小朋友
class Solution {
public static int findContentChildren(int[] g, int[] s) {
// 思路:优先喂饱胃口大的孩子,以免造成浪费
// step1. 从小到大排序胃口和饼干的大小
Arrays.sort(g);
Arrays.sort(s);
// step2.一个变量用于计数(>=0);另一个变量当作指针,指示剩余的饼干量(>=0,可以等于0,数组0位置仍存着一块饼干)
int count = 0;
int start = s.length - 1;
// step3. 从后往前统计剩余的饼干,因为大饼干先分给胃口大的,接着依次分配。
for (int i = g.length - 1; i >= 0; i--) {
// step4. 如果还剩余饼干且这块饼干大于这个小孩的胃口,那么就将这块饼干分给这个小朋友,指针往前指一位,满足的小朋友也+1
if (start >= 0 && g[i] <= s[start]) {
start--;
count++;
}
}
return count;
}
}
解法2:优先喂饱胃口小的小朋友
public static int findContentChildren(int[] g, int[] s) {
// 思路2:先喂饱胃口小的小朋友
// step1 从小到大排序胃口和饼干的大小
Arrays.sort(g);
Arrays.sort(s);
// step2. 一个变量用于计数(>=0);另一个变量当作饼干指针,指示当前第几块饼干
int count = 0;
int start = 0;
// step3. 从前往后分配饼干,只要饼干分量大于小朋友的胃口,就将其喂给小朋友,这里要注意start < g.length(若小朋友都分配到了饼干就应当结束循环)
for (int i = 0; i < s.length && start < g.length; i++) {
if(s[i] >= g[start]) {
count++;
start++;
}
}
return count;
}