알고리즘
100일 동안 매일 알고리즘을 하면? - 8일차
유병각
2022. 1. 7. 14:51
100일 동안 매일 알고리즘을 하면? - 8일차
https://programmers.co.kr/learn/courses/30/lessons/42579
코딩테스트 연습 - 베스트앨범
스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가
programmers.co.kr
이 문제는 dictionary 와 sort 에 대해서 묻는 문제였다. python 에서 딕셔너리와 2차원 배열에 대해서 sort 를 사용하는 방법에 대해서 배울 수 있었다.
def solution(genres, plays):
ret = [];
info = {};
sum = {};
for i in range(len(plays)):
typeOfMusic = genres[i];
play = plays[i];
if typeOfMusic not in info:
info[typeOfMusic] = [];
sum[typeOfMusic] = play;
info[typeOfMusic].append([i, play]);
else:
info[typeOfMusic].append([i, play]);
sum[typeOfMusic] += play;
sum = dict(sorted(sum.items(), key=lambda item: -item[1]));
# reverse = True 은 - 를 붙인것과동일함.
for key in sum.keys():
info[key].sort(key=lambda x: (-x[1], x[0]));
if len(info[key]) == 1:
ret.append(info[key][0][0]);
continue;
for i in range(2):
ret.append(info[key][i][0]);
return ret;
https://codeforces.com/blog/entry/98453
Educational Codeforces Round 120 Editorial - Codeforces
codeforces.com
또한 코드포스에 에디토리얼이 있어서, 각각 문제의 해결방법을 알 수 있었다.
https://programmers.co.kr/learn/courses/30/lessons/42626
코딩테스트 연습 - 더 맵게
매운 것을 좋아하는 Leo는 모든 음식의 스코빌 지수를 K 이상으로 만들고 싶습니다. 모든 음식의 스코빌 지수를 K 이상으로 만들기 위해 Leo는 스코빌 지수가 가장 낮은 두 개의 음식을 아래와 같
programmers.co.kr
import heapq;
def solution(scoville, K):
cnt = 0;
heap = [];
for s in scoville:
heapq.heappush(heap, s);
while(True):
if heap[0] >= K:
return cnt;
if heap[0] < K and len(heap) == 1:
return -1;
num1 = heapq.heappop(heap);
num2 = heapq.heappop(heap);
heapq.heappush(heap, num1 + num2 * 2);
cnt += 1;