455. Assign Cookies
Leetcode 问题: 455. Assign Cookies
Categories:
题目
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 factorg[i]
, which is the minimum size of a cookie that the child will be content with; and each cookie j has a sizes[j]
. Ifs[j]
>=g[i]
, we can assign the cookiej
to the childi
, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.
传入两个阵列,第一个 小孩阵列
,每个数字代表那个小孩 想要的饼乾数量
[1,3,5]
代表
小孩索引 | 0 | 1 | 2 |
---|---|---|---|
想要的饼乾数量 | 1 | 3 | 5 |
第二个阵列代表 饼乾盘阵列
,每个数字代表 那一个盘子有几个饼乾
[3,5,7]
代表
饼乾盘索引 | 0 | 1 | 2 |
---|---|---|---|
有多少饼乾 | 3 | 5 | 7 |
目标是要尽可能将所有小孩餵饱,满足他想要的饼乾,并找出最多能满足几个小孩
Example
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.
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.
答案
- 尽量用
最少的饼乾数量
餵饱需求最少的小孩
,所以要先餵饱满足度较低的小孩
JavaScript
- 将
小孩阵列
与饼乾盘阵列
由小到大排序- 确保
小孩阵列
前面都是满足度较低的小孩 - 确保
饼乾盘阵列
前面都是饼乾数较少的盘子
- 确保
- 设定
小孩检查指标
到第一个满足度较低的小孩索引0
并 设定饼乾盘检查指标
到第一个饼乾数最少的饼乾盘索引0
- 当目前
小孩检查指标
的小孩能够满足,后面的小孩才有可能满足 - 当目前
小孩检查指标
无法满足,后面的小孩也不用检查,肯定吃不饱
- 当目前
- 当
小孩检查指标
的小孩需要的饼乾,是饼乾盘检查指标
的饼乾数可以满足的话- 找到一个可以餵饱的小孩了
- 继续检查下一个小孩
- 继续用下一个饼乾盘检查是否能够餵饱小孩
- 当
小孩检查指标
的小孩需要的饼乾,在饼乾盘检查指标
的饼乾数无法满足- 继续找下一个饼乾盘,看后面的
饼乾盘
有没有足够的数量
可以餵饱小孩
- 继续找下一个饼乾盘,看后面的
/**
* @param {number[]} childrenList
* @param {number[]} cookieList
* @return {number}
*/
var findContentChildren = function(childrenList, cookieList) {
// 将小孩需要的饼乾数量,依照小到大排序
childrenList.sort((a, b) => {
return a - b;
});
// 将拥有饼乾盘子数量,依照小到大排序
cookieList.sort((a, b) => {
return a - b;
});
// 小孩检查指标
let childPointer = 0;
// 饼乾盘检查指标
let cookiePointer = 0;
while (childPointer < childrenList.length && cookiePointer < cookieList.length) {
// 当还没有检查完所有小孩,且也还没检查完所有饼乾盘子,继续检查
if (childrenList[childPointer] <= cookieList[cookiePointer]) {
// 当目前的饼乾盘,可以餵饱小孩,继续找下一个
childPointer++;
cookiePointer++;
} else {
// 当目前的饼乾盘,无法餵饱小孩,继续找下一个
cookiePointer++;
}
}
return childPointer;
};