455. 分发饼干

贪心算法:
1.确定问题最优子结构
2.设计递归算法
3.证明贪心算法安全性
4.将递归转换为迭代

自己解答:

class Solution(object):
    def findContentChildren(self, g, s):
        """
        :type g: List[int]
        :type s: List[int]
        :rtype: int
        """
        g.sort()
        s.sort()
        j = res = 0
        for index in range(len(g)):
            while(j < len(s)):
                if g[index] <= s[j]:
                    res += 1
                    j += 1
                    break
                else:
                    j += 1
        return res

优秀解答:

class Solution(object):
    def findContentChildren(self, g, s):
        """
        :type g: List[int]
        :type s: List[int]
        :rtype: int
        """
        g.sort()
        s.sort()
        index = 0
        count = 0
        for i in s:
            if g[index] <= i:
                count += 1
                index += 1
                if index == len(g):
                    break                
        return count

相关文章: