public class Solution {
    public int FindContentChildren(int[] g, int[] s) {
        var listg = g.OrderBy(x => x).ToList();
            var lists = s.OrderBy(x => x).ToList();

            int i = 0;
            int j = 0;

            int children = 0;

            while (i < listg.Count && j < lists.Count)
            {
                var greed = listg[i];
                var cookie = lists[j];
                if (greed > cookie)
                {
                    j++;
                }
                else
                {
                    //greed<=cookie
                    children++;
                    i++;
                    j++;
                }
            }
            Console.WriteLine(children);
            return children;
    }
}

https://leetcode.com/problems/assign-cookies/#/description

 

补充一个python的实现:

 1 class Solution:
 2     def findContentChildren(self, g: 'List[int]', s: 'List[int]') -> int:
 3         g.sort()#对g排序
 4         s.sort()#对s排序
 5         a, b = 0, 0#设定两个指针,分别指向g和s的0索引
 6         res = 0#记录结果
 7         while a < len(g) and b < len(s):
 8             if g[a] <= s[b]:#满足值<=饼干大小
 9                 res += 1#得到满足的孩子数量+1
10                 a += 1#指向下一个孩子(的满足值)
11                 b += 1#指向下一块饼干(的大小)
12             else:
13                 b += 1#这个孩子不能满足,孩子不动,只移动饼干指针
14         return res

 

posted on 2017-04-19 11:09  Sempron2800+  阅读(111)  评论(0编辑  收藏  举报