LeetCode-455
描述
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i
has a greed factor g[i]
, which is the minimum size of a cookie that the child will be content with; and each cookie j
has a size s[j]
. If s[j] >= g[i]
, we can assign the cookie j
to the child i
, and the child i
will be content. Your goal is to maximize the number of your content children and output the maximum number.
示例
Example 1:
Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
Example 2:
Input: g = [1,2], s = [1,2,3]
Output: 2
Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
Constraints:
1 <= g.length <= 3 * 104
0 <= s.length <= 3 * 104
1 <= g[i], s[j] <= 231 - 1
思路
贪心。把 g 数组和 s 数组排序,然后从最小的饼干开始和最小的食欲进行比较,如果饼干份额大于等于食欲,那么记录满足人数 +1 并对下一块饼干和下一份食欲进行比较,否则用更大的饼干和当前人的食欲进行比较,直到一方为空。
解答
class Solution {
public static void qSort(int[] arr, int low, int high) {
if (low > high) return;
int i = low, j = high, tmp = arr[low];
while (i < j) {
while (tmp <= arr[j] && i < j)
j--;
while (tmp >= arr[i] && i < j)
i++;
if (i < j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
arr[low] = arr[i];
arr[i] = tmp;
qSort(arr, low, j - 1);
qSort(arr, j + 1, high);
}
public static int findContentChildren(int[] g, int[] s) {
if (g.length == 0 || s.length == 0) return 0;
qSort(s, 0, s.length - 1);
qSort(g, 0, g.length - 1);
int cnt = 0;
int i = 0, j = 0;
while (i < s.length && j < g.length) {
if (s[i] >= g[j]) {
cnt++;
j++;
}
i++;
}
return cnt;
}
}
本文来自博客园,作者:klaus08,转载请注明原文链接:https://www.cnblogs.com/klaus08/p/15125788.html