[LeetCode] 455. Assign Cookies 分配饼干

陪她去流浪 桃子 2019年03月12日 编辑 阅读次数:1531

题目

455. Assign Cookies

题意

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 gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, 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.

思路

如果能优先用最小的饼干满足最小贪欲的孩子,那么最终就能满足更多的孩子。此即贪心算法的运用。

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func findContentChildren(g []int, s []int) int {
    sort.Ints(g)
    sort.Ints(s)
    var gi, si int
    for gi < len(g) && si < len(s) {
        if g[gi] <= s[si] {
            gi++
        }
        si++
    }
    return gi
}

标签:算法 · LeetCode · 贪心算法