[프로그래머스] 명예의 전당(1)

Narcoker·2024년 3월 14일
0

코딩테스트

목록 보기
148/150

문제

https://school.programmers.co.kr/learn/courses/30/lessons/138477

풀이

max_heap을 이용한풀이

heapq.heappush(max_heap, (-sc, sc))을 사용해서 큰 순서대로 넣는다.
heapq.nsmallest(k, max_heap) 을 사용해서 큰 순서대로 k개를 가져온다.

nlargest,가 아닌 nsmallest 를 사용하는 이유는 힙 데이터가 배열이나 튜플일 경우
인덱스 0번째 값을 기준으로 한다.

인덱스 0의 값은 최대 힙을 구현하기 위한 우선순위 값이다.
실제 값은 인덱스 1에 저장되어 있다.

import heapq

def solution(k, score):
    answer = []
    max_heap = []
    for sc in score:
        heapq.heappush(max_heap, (-sc, sc))
        answer.append(heapq.nsmallest(k, max_heap)[-1][1])
    return answer
profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글