【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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章