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

相关文章:

  • 2021-11-20
  • 2021-10-11
  • 2021-05-22
  • 2022-02-07
  • 2022-02-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-06
  • 2021-09-02
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案