【leetcode】贪心算法1338 455

  • Online Judge 与算法的特点
    牛客网的是标准的输入输出,leetcode 是写的函数,面试之前要两者都进行训练
  • 贪心的题目
  1. 尝试证明------->可以用贪心
  2. 找反证--------->证明不可以用贪心
  3. 如果没有别的做法,就相信他是贪心,接下来就多加练习
  • 题面破解:
  1. 题面出现 ’最‘ 或者等价的字可能是贪心
  2. 贪心的题目一定有 ’ 最‘ 字
  3. 贪心往往伴随着排序(因为排序就潜在的定义了 贪心提到的 ’ 好‘ )

1338 数组大小减半

class Solution:
    def minSetSize(self, arr: List[int]) -> int:
        count_total = 0
        for i,count in enumerate(sorted(collections.Counter(arr).values(),reverse = True)):
            count_total += count 
            if count_total >= len(arr) / 2:
                return i + 1

455. 分发饼干

class Solution:
    def findContentChildren(self, g, s):
        g.sort(reverse = True)
        s.sort(reverse = True)

        i = j = 0
        while i < len(g) and j < len(s):
            if g[i] <= s[j]:
                j += 1
            i += 1
        return j
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章