81. The algorithm is simple and swift distribution of biscuits

Suppose you are a good parent, you want to give your kids some small biscuits. However, each child can only give a maximum of a biscuit. For each child i, appetite has a value gi, which made the children meet the minimum size biscuits appetite; each biscuit and j, have a size sj. If sj> = gi, we can assign the biscuits to the children j i, the child will be met. Your goal is to meet as much as possible the greater the number of children, and the maximum output value.

note:

You can assume that appetite is positive.
A child can only have up to a biscuit.

Example 1:

Input: [2,3], [1,1]

Output: 1

Explanation: 
You have three children and two small biscuits, three children's appetite values are: 1,2,3.
Although you have two small biscuits because of their size are 1, you can only make the child appetite value 1 is satisfied.
So you should output 1.
Example 2:

Input: [1,2], [2,3]

Output: 2

Explanation: 
You have two children and three biscuits, two children's appetite values are 1,2.
The number and size of cookies that you have enough to make all children are met.
So you should output 2.

solution:

  func findContentChildren(_ g: [Int], _ s: [Int]) -> Int {
     var s = s
        var g = g
        g.sort()
        s.sort()
        var gi = 0
        var si = 0
        var res = 0
        //贪心算法
        while gi < g.count && si < s.count{
            if s[si] >= g[gi]{
                si += 1
                gi += 1
                res += 1
            }else{
                si += 1
            }
        }
        return res
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/93459823