455. Assign Cookies

来源:互联网 发布:2016淘宝刷单技巧 编辑:程序博客网 时间:2024/06/02 19:41
  • 超时了
class Solution(object):    def findContentChildren(self, g, s):        """        :type g: List[int]        :type s: List[int]        :rtype: int        """        count = 0        k=[] //已经满足的小孩的编号        for i in range(len(s)):            for j in range(len(g)):                if s[i] >= g[j] and j not in k:                    count += 1                    k.append(j)                    break        return count
  • 正确方法
class Solution(object):    def findContentChildren(self, g, s):        """        :type g: List[int]        :type s: List[int]        :rtype: int        """               g.sort()        s.sort()        g_count,s_count = 0,0        while g_count<len(g) and s_count < len(s):            if s[s_count] >= g[g_count]:                g_count += 1            s_count += 1        return g_count

这种方法非常直观,一种贪心的策略,如果排序后的糖果满足排序后的小孩的需求,都向后一个;如果没有满足,那这个糖果也就无法满足之后的小孩的需求了,所以糖果编号再向后移动一个

0 0
原创粉丝点击