기억은 짧고 기록은 길다
[프로그래머스/Programmers] 더 맵게 - Python 본문
Link
코딩테스트 연습 - 더 맵게
매운 것을 좋아하는 Leo는 모든 음식의 스코빌 지수를 K 이상으로 만들고 싶습니다. 모든 음식의 스코빌 지수를 K 이상으로 만들기 위해 Leo는 스코빌 지수가 가장 낮은 두 개의 음식을 아래와 같
programmers.co.kr
Solution
해당 문제를 heapq를 사용하지 않고 해결해보려고 했으나 계속 효율성 문제에 걸려 결국 heapq를 사용하였다.
heapq에 대한 자세한 설명은 하단 첨부링크를 확인하기 바란다.
def solution(scoville, K):
answer = 0
scoville.sort()
while True:
if scoville[0] < K:
scoville[1] = scoville[0] + scoville[1] * 2
del scoville[0]
answer += 1
scoville.sort()
t = scoville[0] >= K
if t == False and len(scoville) == 1:
return -1
elif t == True:
return answer
import heapq
def solution(scoville, K):
answer = 0
heapq.heapify(scoville)
while True:
if scoville[0] < K:
t = heapq.heappop(scoville) + heapq.heappop(scoville) * 2
heapq.heappush(scoville, t)
answer += 1
if len(scoville) == 1 and scoville[0] < K:
return -1
if scoville[0] >= K:
return answer
🔑 key point: heapq
첨부
'CodingTest > programmers' 카테고리의 다른 글
[프로그래머스/Programmers] 문자열 압축 - Python (0) | 2021.09.17 |
---|---|
[프로그래머스/Programmers] 땅 따먹기 - Python (0) | 2021.09.16 |
[프로그래머스/Programmers] 다음 큰 숫자 - Python (0) | 2021.09.15 |
[프로그래머스/Programmers] 다리를 지나는 트럭 - Python (0) | 2021.09.14 |
[프로그래머스/Programmers] 기능개발 - Python (0) | 2021.09.14 |
Comments