https://programmers.co.kr/learn/courses/30/lessons/42579
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from collections import defaultdict
def solution(genres, plays):
d = defaultdict(list)
for i, (g, p) in enumerate(zip(genres, plays)):
d[g].append((p, -i))
d = {k: sorted(v) for k, v in d.items()}
n_totals = {k: sum([v[0] for v in vs]) for k, vs in d.items()}
n_totals = dict(sorted(n_totals.items(), key=lambda item: item[1], reverse=True))
answer = []
for g in n_totals:
for i in range(2):
try:
answer.append(-d[g].pop()[1])
except:
pass
return answer
Complexity
$O(|genres|)$
PREVIOUSEtc