当前位置 博文首页 > OIqng的博客:Leetcode——455 Assign Cookies(分发饼干)

    OIqng的博客:Leetcode——455 Assign Cookies(分发饼干)

    作者:[db:作者] 时间:2021-07-14 10:06

    题目:

    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.

    假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
    对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

    示例 1:

    输入: g = [1,2,3], s = [1,1]
    输出: 1
    解释:
    你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
    虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
    所以你应该输出1。

    示例 2:

    输入: g = [1,2], s = [1,2,3]
    输出: 2
    解释:
    你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
    你拥有的饼干数量和尺寸都足以让所有孩子满足。
    所以你应该输出2.

    提示:

    1 <= g.length <= 3 * 1 0 4 10^4 104
    0 <= s.length <= 3 * 1 0 4 10^4 104
    1 <= g[i], s[j] <= 2 31 2^{31} 231 - 1

    首先对数组 g 和 s 排序,然后从小到大遍历 g 中每个元素,对于每个元素找到能满足该元素的 s 中的最小的元素。对于每个元素 g[i],找到未被使用的最小的 j 使得 g[i]≤s[j],则 s[j] 可以满足 g[i]。由于 g 和 s 已经排好序,因此整个过程只需要对数组 g 和 s 各遍历一次。当两个数组遍历结束时,说明所有的孩子都被分配到了饼干,或者所有的饼干都已经被分配或被尝试分配(可能有些饼干无法分配)。

    class Solution:
        def findContentChildren(self, g: List[int], s: List[int]) -> int:
            g.sort()
            s.sort()
            n, m = len(g), len(s)
            i = j = count = 0
            while i < n and j < m:
                if  g[i] > s[j]:
                    j += 1
                else:
                    count += 1
                    i += 1
                    j += 1
            return count
    

    复杂度分析

    时间复杂度:O(mlogm+nlogn),其中 m 和 n 分别是数组 g 和 s 的长度。对两个数组排序的时间复杂度是 O(mlogm+nlogn),遍历数组的时间复杂度是 O(m+n),因此总时间复杂度是 O(mlogm+nlogn)。

    空间复杂度:O(logm+logn),其中 m 和 n 分别是数组 g 和 s 的长度。空间复杂度主要是排序的额外空间开销。

    在这里插入图片描述

    cs