题目:
题解:排序 + 贪心算法
代码:排序 + 贪心算法
import java.util.Arrays;
public class lc_455 {
public static int findContentChildren(int[] g, int[] s) {
// 先对胃口值和饼干尺寸进行排序
Arrays.sort(g); // 孩子的胃口值g[i]
Arrays.sort(s); // 饼干的尺寸s[j]
int count = 0; // 满足胃口值的孩子的数量
for (int j = 0; count < g.length && j < s.length; j++) {
// 如果当前饼干能满足当前孩子的胃口值,可以满足的孩子数量count就加1,否则就继续查找更大的饼干
if (g[count] <= s[j]) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int g1[] = {1, 2, 3};
int s1[] = {1, 1};
int res1 = findContentChildren(g1, s1);
System.out.println(res1);
int g2[] = {1, 2};
int s2[] = {1, 2, 3};
int res2 = findContentChildren(g2, s2);
System.out.println(res2);
}
}