๐ŸŒฑ → ๐ŸŒณ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ - python ๋ณธ๋ฌธ

Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ - python

BAY 2023. 11. 9. 10:47
728x90

์ฝ”๋“œ

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

 

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ ์งˆ๋ฌธ · Issue #1 · lake041/sesac-algorithm

๋ฌธ์ œ ๋งํฌ : ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ 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...

github.com

 

 

๋ญ”๊ฐ€ ์ด ๋ฌธ์ œ์—์„œ ์‹ค์งˆ์ ์œผ๋กœ ์›ํ•œ๊ฑด 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]

์ด๊ฒŒ ์ •์„ ํ’€์ด์ธ๋“ฏ ?

728x90