leetcode 455. Greedy algorithm for distributing cookies

Example 1:

Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation:
You have three children and two biscuits. The appetite values ​​of the three children are: 1, 2, 3.
Although you have two small biscuits, since their size is 1, you can only satisfy the child whose appetite is 1.
So you should output 1.

Example 2:

Input: g = [1,2], s = [1,2,3]
Output: 2
Explanation:
You have two children and three biscuits, and the appetites of the two children are 1,2 respectively.
The number and size of cookies you have are enough to satisfy all children.
So you should output 2.

First, sort the two lists.
The principle of distribution is that the small one is given to the small one, and the big one is given to the large one. To be
precise, the smallest one that satisfies the child’s needs is selected from the remaining biscuits every time. Every time
a child is satisfied, one kid is added.
Finally, if the remaining biscuits cannot meet the needs of the child
, return to kid
, and return the number of children len(s)

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

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/111678113