관리 메뉴

제로부터시작하는개발세계

프로그래머스 Level1 명예의 전당 Python 본문

알고리즘

프로그래머스 Level1 명예의 전당 Python

자바시러 2022. 11. 26. 00:59

문제 링크

풀이

heap을 사용해서 heap크기가 k보다 같거나 커졌을 경우 젤 작은 값과 비교해서 클 경우 넣어준다.

현재 heap에서 가장 값이 작은 0번째 인덱스를 answer에 넣어주면 정답.

 

제한사항

  • 3 ≤ k ≤ 100
  • 7 ≤ score의 길이 ≤ 1,000
    • 0 ≤ score[i] ≤ 2,000

정답 코드

import heapq
def solution(k, score):
    answer = []
    heap = []
    for i in range(len(score)): 
        if len(heap) >= k:
            if heap[0] < score[i]:
                heapq.heappop(heap)
                heapq.heappush(heap,score[i])
        else:
            heapq.heappush(heap,score[i])
        answer.append(heap[0])
    return answer