题目
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。
你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
思路
1.尽可能让更多的孩子吃饼干
2.胃口小的吃小的,胃口大的吃大的
先对两个数组进行排序
遍历S数组,如果能喂饱孩子,就进行下一轮并且count++
如果喂不饱则无事发生进行下一轮的投喂
直到喂完孩子为止
方法
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
for (int i = 0; i < s.length; i++) {
if(s[i] >= g[count]) {
count++;
if(count == g.length) {
break;
}
}
}
return count;
}
官方答案
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int numOfChildren = g.length, numOfCookies = s.length;
int count = 0;
for (int i = 0, j = 0; i < numOfChildren && j < numOfCookies; i++, j++) {
while (j < numOfCookies && g[i] > s[j]) {
j++;
}
if (j < numOfCookies) {
count++;
}
}
return count;
}
解题步骤:
先对两个数组进行排序
遍历两个数组,然后while循环进行判断,j < numOfCookies 并且 孩子的胃口大于饼干, j 就自增,然后继续判断,直到判断不成立。
这时候如果 j 小于数组S的长度,就记一次数 count++
然后 i 自增,进行下一轮判断。
总结
感觉两种方法差不多,第一种方法可能更直接一些