본문 바로가기
Leetcode

[LeetCode] Assign Cookies 파이썬 (greedy)

by YGSEO 2021. 4. 17.
728x90
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()

        result, i = 0, 0
        for j in range(len(s)):
            if i == len(g):
                break
            if s[j] >= g[i]:
                result += 1
                i += 1
        return result

우선 sort 하고

 

two pointer(i,j)

i를 g의 pointer로 사용하고

j는 s의 pointer로 사용하면서

하나씩 체크해 나간다.

i == len(g) 를 통해 g의 모든 element를 체크했으면 exit

s의 j-th 원소와 g의 i-th 원소를 비교하면서 조건에 맞으면

result에 count + 1

i를 한칸 옆으로 이동.(children received cookies)

 

출처: github.com/jiapengwen/LeetCode/blob/master/Python/assign-cookies.py

 

728x90

댓글