[Level3] 단속카메라

Quesuemon·2021년 3월 30일
0

코딩테스트 준비

목록 보기
43/111

🛠 문제

https://programmers.co.kr/learn/courses/30/lessons/42884


👩🏻‍💻 해결 방법

routes 리스트를 x[1](나간 지점) 기준으로 오름차순 정렬해주었다
camera 변수는 -30001로 설정하여 최소 진입지점보다 작은 수로 설정했다
만약 routes[i][0](진입 지점)이 camera보다 크다면,
answer+1을 해주고 camera를 routes[i][1]로 바꾸어 준다

소스 코드

def solution(routes):
    answer = 0
    routes.sort(key = lambda x:x[1])
    camera = -30001
    
    for r in routes:
        if camera < r[0]:
            answer += 1
            camera = r[1]
    return answer

💡 다른 사람의 풀이

import heapq

def solution(routes):
    routes.sort(key=lambda x:x[0])

    answer = 0
    h = [30001]
    for r in routes:
        earliestend = heapq.heappop(h)
        if r[0] > earliestend:
            answer += 1
            h.clear()
        else:
            heapq.heappush(h, earliestend)
        heapq.heappush(h, r[1])
    else:
        if len(h) != 0:
            answer += 1
    return answer

0개의 댓글