先看題目
解決思路 先將g數組和s數組排序,使得最小的餅乾和最小胃口的孩子做匹配,如果滿足,將計數變量ret加1,如果不滿足,則尋找更大的餅乾來滿足孩子的胃口。代碼
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int ret = 0;
int gi = 0;
for (int i = 0; i < s.length; i++) {
for (int j = gi; j < g.length; j++) {
if (s[i] >= g[j]) {
ret++;
j= ++gi;
break;
}
}
}
return ret;
}
}