[๋ฌธ์ ๋งํฌ] ๐
ํ๋ก๊ทธ๋๋จธ์ค
SW๊ฐ๋ฐ์๋ฅผ ์ํ ํ๊ฐ, ๊ต์ก, ์ฑ์ฉ๊น์ง Total Solution์ ์ ๊ณตํ๋ ๊ฐ๋ฐ์ ์ฑ์ฅ์ ์ํ ๋ฒ ์ด์ค์บ ํ
programmers.co.kr
ํ์ด ๋ฐฉ๋ฒ
1๏ธโฃ ๋ช ์์ ์ ๋น ์ ์ง
- ๋ช ์์ ์ ๋น์ k ๊ฐ์ ์ ์๋ฅผ ์ ์งํ๋ฉฐ, kk๊ฐ๋ฅผ ์ด๊ณผํ๋ฉด ๊ฐ์ฅ ๋ฎ์ ์ ์๋ฅผ ์ ๊ฑฐ
- ์ฐ์ ์์ ํ(์ต์ ํ)๋ฅผ ํ์ฉํ๋ฉด ํจ์จ์ ์ผ๋ก ๊ด๋ฆฌ ๊ฐ๋ฅ
2๏ธโฃ ์ตํ์ ์ ์ ์ถ์ถ
- ๋งค๋ฒ ๋ช ์์ ์ ๋น์์ ์ตํ์ ์ ์๋ฅผ ํ์ธํ์ฌ ๊ธฐ๋ก
3๏ธโฃ ์ ์ ์ฒ๋ฆฌ
- ์ ์๋ฅผ ํ๋์ฉ ์ถ๊ฐํ๋ฉฐ ๋ช ์์ ์ ๋น์ ์ ๋ฐ์ดํธ
- ๋ช ์์ ์ ๋น์ด ๊ฐ๋ ์ฐจ๋ฉด ์ต์ ์ ์์ ๋น๊ต ํ ๋์ฒด
Solution
์ต์ ํ ๊ตฌํ
import heapq
def solution(k, score):
hall_of_fame = [] # ๋ช
์์ ์ ๋น (์ต์ ํ)
result = []
for s in score:
heapq.heappush(hall_of_fame, s) # ์ ์ ์ถ๊ฐ
if len(hall_of_fame) > k: # ํฌ๊ธฐ ์ด๊ณผ ์ ์ต์๊ฐ ์ ๊ฑฐ
heapq.heappop(hall_of_fame)
result.append(hall_of_fame[0]) # ํ์ฌ ๋ช
์์ ์ ๋น์ ์ตํ์ ์ ์ ๊ธฐ๋ก
return result
- heapq ์ฌ์ฉ
- ์ต์ ํ์ผ๋ก ๋ช ์์ ์ ๋น ์ ์๋ฅผ ๊ด๋ฆฌ
- ์ ์ ์ถ๊ฐ ๋ฐ ์ญ์ ์ ๋ก ์ฒ๋ฆฌ ๊ฐ๋ฅ
- result์ ์ตํ์ ์ ์ ์ถ๊ฐ
- ๋งค์ผ ๋ช ์์ ์ ๋น์์ ๊ฐ์ฅ ๋ฎ์ ์ ์๋ฅผ ๊ฒฐ๊ณผ ๋ฆฌ์คํธ์ ์ถ๊ฐ
- ์๊ฐ ๋ณต์ก๋
- ์ ์ ๋ฐฐ์ด์ ๊ธธ์ด๊ฐ ์ผ ๋, ์ต๋ O(nlogโกk)
๋จ์ ๊ตฌํ
def solution(k, score):
answer = []
top = []
for s in score:
top.append(s)
if len(top) > k: # ๋ช
์์ ์ ๋น ํฌ๊ธฐ๋ฅผ ์ด๊ณผํ๋ฉด ์ต์๊ฐ ์ ๊ฑฐ
top.remove(min(top))
answer.append(min(top)) # ํ์ฌ ๋ช
์์ ์ ๋น์ ์ตํ์ ์ ์ ๊ธฐ๋ก
return answer
'๐งฉ Algorithm > [Programmers] Level 2' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Programmers] L2. ๋ฉ๋ฆฌ ๋ฐ๊ธฐ (Python) (0) | 2024.12.02 |
|---|---|
| [Programmers] L2. ๊ทค ๊ณ ๋ฅด๊ธฐ (Greedy/Python) (0) | 2024.11.16 |
| [Programmers] L2. ๊ตฌ๋ช ๋ณดํธ (Python/ํฌ ํฌ์ธํฐ) (0) | 2024.11.15 |
| [Programmers] L2. ์์ด ๋๋ง์๊ธฐ (Python) (1) | 2024.11.11 |
| [Programmers] L2. ์ ํ์ ์๊ฐ ์ด๋ (Python) (0) | 2024.11.11 |