1、描述
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
2、提示:
a. 1 <= g.length <= 3 * 104
b. 0 <= s.length <= 3 * 104
c. 1 <= g[i], s[j] <= 2^31 - 1
3、思路
从 尽可能以一个最小尺寸饼干 来满足一个孩子的胃口。
因此 从 排序+贪心+双指针角度。
排序:将 尺寸 和 胃口 分别升序。
贪心+双指针:胃口指针i和尺寸指针j分别从 首元素即最小的开始遍历,只有g[i] <= s[j],i指针才会移动,而j指针一直移动。
边界条件是 任意1个指针移动到其边界。
4、代码
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
s = sorted(s)
g = sorted(g)
len1, len2 = len(g), len(s)
ans = 0
i, j = 0, 0
while True:
if i == len1 or j == len2:
break
if g[i] <= s[j]:
ans += 1
i, j = i + 1, j + 1
else:
j += 1
return ans