์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- ํฌ๋กค๋ง
- error
- ๊ตญ๋น์ง์
- ํ์ด์ฌ
- ์๊ณ ๋ฆฌ์ฆ
- ์ฝ๋ฉํ ์คํธ
- heapq
- react
- ๊ฐ๋ฐ
- ํ๋ก๊ทธ๋๋จธ์ค
- JS
- ํ๋ก ํธ์๋
- ์ฝ๋ฉ์ ํ
- ๋๋ฆผ์ฝ๋ฉ
- CSS
- ๊ทธ๋ฆฌ๋
- fe
- ์ฝ๋ฉ
- ๋ฐฑ์ค
- HTML
- KDT
- mongodb
- node.js
- Til
- ๋ ธ๋ง๋์ฝ๋
- ํ ์ดํ๋ก์ ํธ
- Python
- ํ๋ก์ ํธ
- ๋ชจ๊ฐ์ฝ
- javascript
- Today
- Total
๐ฑ → ๐ณ
[ํ๋ก๊ทธ๋๋จธ์ค] ์ด์ค์ฐ์ ์์ํ - python ๋ณธ๋ฌธ
์ฝ๋
from heapq import *
def solution(operations):
q = []
for i in operations:
op, n = i.split()
if op == 'I':
heappush(q, int(n))
elif op == 'D' and len(q) != 0:
if n == "-1":
heappop(q)
else:
q.sort()
q.pop()
if q:
return [max(q), q[0]]
else:
return [0,0]
max๊ฐ ๋ฆฌํ ๋ ธ๋์ ์๋ค๋ ๊ฒ์ ๋ณด์ฅ๋์ง๋ง ๊ฐ์ฅ ๋ ๋ ธ๋(์ธ๋ฑ์ค)์ ์๋ค๋ ๊ฒ์ ๋ณด์ฅ๋์ง ์๊ธฐ ๋๋ฌธ์ q.sort() ํด์ค
์ต๋๊ฐ ๋บ ๋ q.sort() ํ๋๋ฐ ํธ๋ฆฌ ๊ตฌ์กฐ๊ฐ ์๋ฌด๋์ง๋ค
์ ๋ค ํต๊ณผํ์ง
..?
heappop, heappush ํ ๋ ํธ๋ฆฌ๊ตฌ์กฐ๋ฅผ ๋์ฐพ๋๊ฑด์ง ์๋๋ฉด ํ ์ผ๊ฐ ๋ถ์กฑํด์ ์ด์ข๊ฒ ํต๊ณผํ๊ฑด์ง ๋ชฐ๊ฒ ์ด
์๋ฌธ ํด๊ฒฐ ๊ณผ์
https://github.com/lake041/sesac-algorithm/issues/1
๋ญ๊ฐ ์ด ๋ฌธ์ ์์ ์ค์ง์ ์ผ๋ก ์ํ๊ฑด max_heap, min_heap ์ด๋ ๊ฒ heapq๋ฅผ 2๊ฐ๋ฅผ ๋ง๋ค์ด์ ๋๊ธฐํํด๊ฐ๋ฉด์ ํธ๋ ๋ฐฉ๋ฒ์ด์์ ๊ฒ ๊ฐ์๋ฐ ๋๊ธฐํ ๋ฐฉ๋ฒ์ด ๋ง๋ ํ ๋ ์ค๋ฅด์ง ์์
๋ฌธ์ ์์ฒด๊ฐ ํ ์ผ๊ฐ ๋ง์ด ๋ถ์กฑํด์ ์ ํํ๊ฒ ๋ง๋์ง๋ ๋ชจ๋ฅด๊ฒ ์
์ผ๋จ ํต๊ณผํ๊ธด ํ๋๋ฐ ..
from heapq import heappush, heappop
def solution(operations):
maxq, minq = [], []
deleted_index = []
for i in range(len(operations)):
op, num = operations[i].split()
num = int(num)
if op=="I":
heappush(maxq, (-num, i))
heappush(minq, (num, i))
elif num == 1:
if maxq:
_, index = heappop(maxq)
deleted_index.append(index)
elif num == -1:
if minq:
_, index = heappop(minq)
deleted_index.append(index)
while minq and minq[0][1] in deleted_index:
heappop(minq)
while maxq and maxq[0][1] in deleted_index:
heappop(maxq)
return [-heappop(maxq)[0], heappop(minq)[0]] if maxq else [0, 0]
์ด๊ฒ ์ ์ ํ์ด์ธ๋ฏ ?
'Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Baekjoon] 11501๋ฒ. ์ฃผ์ - python (1) | 2024.01.09 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค] ์์ - python (1) | 2023.10.30 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์ ํ๋ฒํธ ๋ชฉ๋ก - python (0) | 2023.10.30 |
[Baekjoon] 4963. ์ฌ์ ๊ฐ์ - python (0) | 2023.10.27 |
[Baekjoon] 1926. ๊ทธ๋ฆผ - python (0) | 2023.10.03 |