[LeetCode] 455. Assign Cookies

김민우·2022년 12월 31일
0

알고리즘

목록 보기
102/189

- Problem

455. Assign Cookies


- 내 풀이 (sort, greedy)

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        M, N = len(g), len(s)
        i, j = 0, 0

        while i < M and j < N:
            if g[i] <= s[j]:
                i += 1
            j += 1
        
        return i

- 결과

- 내 풀이 (heap)

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        heapq.heapify(g)
        heapq.heapify(s)
        answer = 0

        while g and s:
            i, j = heapq.heappop(g), heapq.heappop(s)

            if i <= j:
                answer += 1
            
            else:
                heapq.heappush(g, i)
        
        return answer

or

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        heapq.heapify(g)
        heapq.heapify(s)
        answer = 0

        while g and s:
            if g[0] <= s[0]:
                heapq.heappop(g)
                answer += 1
            
            heapq.heappop(s)
        
        return answer

- 결과

profile
Pay it forward.

0개의 댓글