假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
输入: [1,2,3], [1,1]
输出: 1
因为有三个孩子,所提供尺寸只能满足胃口值为1的孩子,其余不满足,故输出1.
一、方法与思路
采用贪心算法的思想,即
优先满足胃口值小的,
且优先用小尺寸满足胃口值小的。
则大致思路如下:
先顺序排列胃口值g与尺寸值s,
从小到大开始遍历两个数组:
如果当前g[child]<=s[cookie],则可以满足该孩子的胃口,
否则,cookie++,看下一个饼干的大小能否满足对应孩子的胃口。
C++代码
#include <stdio.h>
#include <vector>
#include <algorithm>
class Solution {
public:
int findContentChildren(std::vector<int>& g, std::vector<int>& s) {
std::sort(g.begin(), g.end());
std::sort(s.begin(), s.end());
int child = 0;
int cookie = 0;
while(child < g.size() && cookie < s.size()){
if (g[child] <= s[cookie]){
child++;
}
cookie++;
}
return child;
}
};
int main(){
Solution solve;
std::vector<int> g;
std::vector<int> s;
g.push_back(5);
g.push_back(10);
g.push_back(2);
g.push_back(9);
g.push_back(15);
g.push_back(9);
s.push_back(6);
s.push_back(1);
s.push_back(20);
s.push_back(3);
s.push_back(8);
printf("%d\n", solve.findContentChildren(g, s));
return 0;
}
Python代码
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g = sorted(g,reverse=True)
s = sorted(s,reverse=True)
child = cookie = 0
while child != len(g) and cookie != len(s):
if g[child] <= s[cookie]:
j += 1
child += 1
cookie += 1
return child