leedcode-分發餅乾(貪心演算法)

Junior_bond發表於2024-05-07

自己寫的,沒有使用排序 ,會超出時間限制:

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        if len(s)==0:
            return 0
        count=0
        for i in range(len(g)):
            mydict = {}
            for j in range(len(s)):
                if s[j]==g[i]:
                    s[j]=-100
                    count+=1
                    mydict={}
                    break
                elif s[j]>g[i] :
                    mydict.update({s[j]:j})
            if len(mydict)!=0:
                min_key=min(mydict.keys())
                s[mydict[min_key]]=-100
                count += 1

        return count

使用sort():

class Solution:
    def findContentChildren(self, children: List[int], cookies: List[int]) -> int:
        # 將孩子的胃口和餅乾排序
        children.sort()
        cookies.sort()
        # 孩子的數量
        num_children = len(children)
        # 餅乾的數量
        num_cookies = len(cookies)
        # 記錄結果
        satisfied_children = 0 
        for i in range(num_cookies):
            # 從胃口小的孩子開始喂
            if satisfied_children < num_children and children[satisfied_children] <= cookies[i]:
                satisfied_children += 1
        return satisfied_children

相關文章