728x90
1. ๋ฌธ์ ์์ฝ
์คํธ๋ฆฌ๋ฐ ์ฌ์ดํธ์์ ์ฅ๋ฅด๋ณ๋ก ๊ฐ์ฅ ๋ง์ด ์ฌ์๋ ๋ ธ๋๋ฅผ ๋ ๊ฐ์ฉ ๋ชจ์ ๋ฒ ์คํธ ์จ๋ฒ์ ์ถ์ํ๋ค.
๋ ธ๋ ์ ์ ๊ธฐ์ค์ ๋ค์๊ณผ ๊ฐ๋ค: ์ํ ๋ ธ๋๊ฐ ๋ง์ด ์ฌ์๋ ์ฅ๋ฅด → ์ฅ๋ฅด ๋ด์์ ๋ง์ด ์ฌ์๋ ๋ ธ๋ → ์ฌ์ ์๊ฐ ๊ฐ๋ค๋ฉด ๊ณ ์ ๋ฒํธ๊ฐ ๋ฎ์ ๋ ธ๋ ์์์ด๋ค.
2. ํต์ฌ ํฌ์ธํธ
- โ
๋ฐ์ดํฐ ๊ทธ๋ฃนํ:
defaultdict๋ฅผ ์ฌ์ฉํ์ฌ ์ฅ๋ฅด๋ณ ์ด ์ฌ์ ์์ ๊ณก ์ ๋ณด๋ฅผ ํ ๋ฒ์ ์ ๋ฆฌํ๋ค. - โ
๋ค์ค ์กฐ๊ฑด ์ ๋ ฌ: Python์
sortedํจ์์lambda๋ฅผ ํ์ฉํ์ฌ ๋ณต์กํ ์ ๋ ฌ ์ฐ์ ์์๋ฅผ ์ฒ๋ฆฌํ๋ค.
3. ๊ตฌํ ์ฝ๋ (Python)
from collections import defaultdict
def solution(genres, plays):
play_count = defaultdict(int)
genre_songs = defaultdict(list) # ์ฅ๋ฅด๋ณ ๊ณก ๊ทธ๋ฃนํ
# 1. ํ ๋ฒ์ ์ํ๋ก ๋ฐ์ดํฐ ์ ๋ฆฌ
for i, (genre, play) in enumerate(zip(genres, plays)):
play_count[genre] += play
genre_songs[genre].append((play, i))
# 2. ์ฅ๋ฅด ์ ๋ ฌ (์ด ์ฌ์ ์ ๊ธฐ์ค ๋ด๋ฆผ์ฐจ์)
sorted_genres = sorted(play_count, key=lambda x: play_count[x], reverse=True)
answer = []
# 3. ์ฅ๋ฅด๋ณ ์์ 2๊ณก ์ถ์ถ
for genre in sorted_genres:
# ์ฌ์ ์ ๋ด๋ฆผ์ฐจ์(-x[0]), ์ธ๋ฑ์ค ์ค๋ฆ์ฐจ์(x[1])
sorted_songs = sorted(genre_songs[genre], key=lambda x: (-x[0], x[1]))
for play, i in sorted_songs[:2]:
answer.append(i)
return answer
๐ ๋์ ์์ฑ: play_count๋ ์ฅ๋ฅด๋ณ ์ฌ์ ํฉ๊ณ๋ฅผ, genre_songs๋ ๊ณก ๋ฆฌ์คํธ๋ฅผ ๊ด๋ฆฌํ๋ค.
๐ ๋ค์ค ์ ๋ ฌ: key=lambda x: (-x[0], x[1])์ ๊ฐ์ด ํํ์ ๋ฐํํ๋ฉด ์ฒซ ๋ฒ์งธ ๊ธฐ์ค์ด ๊ฐ์ ๋ ๋ ๋ฒ์งธ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌํ๋ค.
4. ๋ฐ์ดํฐ ์๊ฐํ
# play_count ์์
{'pop': 3100, 'classic': 1450}
# genre_songs ์์
{'classic': [(500, 0), (150, 2), (800, 3)], 'pop': [(600, 1), (2500, 4)]}
728x90
'๐งฉ Algorithm > [Programmers] ์๊ณ ๋ฆฌ์ฆ ๊ณ ๋์ KIT' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Programmers/์๊ณ ๋ฆฌ์ฆ ๊ณ ๋์ KIT] ๊ธฐ๋ฅ๊ฐ๋ฐ (0) | 2026.04.01 |
|---|---|
| [Programmers/์๊ณ ๋ฆฌ์ฆ ๊ณ ๋์ KIT] ๊ฐ์ ์ซ์๋ ์ซ์ด (0) | 2026.03.31 |
| [Programmers/์๊ณ ๋ฆฌ์ฆ ๊ณ ๋์ KIT] ์์ (0) | 2026.03.21 |
| [Programmers/์๊ณ ๋ฆฌ์ฆ ๊ณ ๋์ KIT] ์ ํ๋ฒํธ ๋ชฉ๋ก (0) | 2026.03.19 |
| [Programmers/์๊ณ ๋ฆฌ์ฆ ๊ณ ๋์ KIT] ํฌ์ผ๋ชฌ (0) | 2026.03.18 |