[알고리즘] 투 포인터_티셔츠 Python

김승연·2023년 6월 18일

💡 강의 참고 전 코드 (성공)

# 자신의 상의 크기와 같거나 큰 티셔츠를 받는다.

# people 하나씩 탐색하면서 같거나 큰 티셔츠 찾음
# 이중 for문 N^2 -> 5,000*5,000 = 25,000,000 
from collections import deque

def solution(people, tshirts):
    answer = 0
    # people과 tshirts 모두 오름차순 정렬
    people_dq = deque(sorted(people))
    tshirts_dq = deque(sorted(tshirts))
    
    while (people_dq):
        person = people_dq.popleft()
        while (tshirts_dq):
            tshirt = tshirts_dq.popleft()
            if person <= tshirt: # 같거나 큰 티셔츠 찾을 때까지 반복
                answer += 1
                break

    return answer

💡 문제 설명 및 강사님 풀이

def solution(people, tshirts):
    people.sort()
    tshirts.sort()
    p, t, ans = 0, 0, 0
    while p < len(people) and t < len(tshirts):
        if tshirts[t] >= people[p]:
            ans += 1
            p += 1
        t += 1
    return ans

후기

나는 deque 자료형을 이용해서 풀었는데, 이렇게 투포인터를 사용하면 코드가 훨씬 간결해진다.
두 리스트를 탐색하며 비교할 땐 투 포인터 알고리즘을 사용해보자.

0개의 댓글