제로부터시작하는개발세계
프로그래머스 Level1 명예의 전당 Python 본문
문제 링크
풀이
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
'알고리즘' 카테고리의 다른 글
프로그래머스 Level3 부대복귀 Python (0) | 2022.12.01 |
---|---|
프로그래머스 Level4 2019카카오 겨울 인턴십 호텔 방 배정 Python (0) | 2022.11.29 |
프로그래머스 Level2 귤 고르기 Python (0) | 2022.11.24 |
프로그래머스 Level2 롤케이크 자르기 Python (0) | 2022.11.24 |
프로그래머스 Level2 2018 카카오 [1차] 캐시 Python (0) | 2022.11.23 |