455. Assign Cookies

xiaoxiao2021-02-28  112

超时了 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

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

转载请注明原文地址: https://www.6miu.com/read-42367.html

最新回复(0)