๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [Python] [Level3] ์ด์ค‘ ์šฐ์„ ์ˆœ์œ„ ํ

Dbswnstjd 2023. 4. 11. 15:27

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/42628

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 3๋‹จ๊ณ„ - ์ด์ค‘ ์šฐ์„ ์ˆœ์œ„ ํ
import heapq
def solution(operations):
    heap = []
    max_heap = []
    
    for o in operations:
        current = o.split()
        if current[0] == 'I':
            num = int(current[1])
            heapq.heappush(heap, num) # ์ตœ์†Œ ํž™
            heapq.heappush(max_heap, (num*-1, num)) # ์ตœ๋Œ€ ํž™
        else:
            if len(heap) == 0:
                pass
            elif current[1] == '1':
                max_value = heapq.heappop(max_heap)[1]
                heap.remove(max_value)
            elif current[1] == '-1':
                min_value = heapq.heappop(heap)
                max_heap.remove((min_value*-1, min_value))
    
    if heap:
        return [heapq.heappop(max_heap)[1], heapq.heappop(heap)]
    else:
        return [0,0]
print(solution(["I 16", "I -5643", "D -1", "D 1", "D 1", "I 123", "D -1"]))

์ด์ค‘ ์šฐ์„ ์ˆœ์œ„ ํ ๋ฌธ์ œ์ด๋‹ค. ์šฐ์„ ์ˆœ์œ„ ํ๋Š” ํž™ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ํ†ตํ•ด ๊ตฌํ˜„์ด ๊ฐ€๋Šฅํ•˜๋‹ค. 

๋‚ด๊ฐ€ ์“ด ๋ฐฉ๋ฒ•์€ ๊ธฐ๋ณธ์ ์œผ๋กœ ํž™ ์ž๋ฃŒ๊ตฌ์กฐ๋กœ ๋งŒ๋“œ๋Š” ์šฐ์„ ์ˆœ์œ„ ํ๋Š” ์ตœ์†Œ ํž™์ด๋ฏ€๋กœ ์ตœ๋Œ€ ํž™์„ ๋”ฐ๋กœ ๊ตฌํ˜„ ํ•˜๊ณ 

์ตœ์†Œ๊ฐ’์„ ๋นผ์•ผํ•˜๋ฉด ์ตœ์†Œํž™์—์„œ pop์„ ํ•ด์ฃผ๊ณ  ์ตœ๋Œ€ํž™์—์„œ remove๋ฅผ ํ•ด์ค€๋‹ค.

์ตœ๋Œ€๊ฐ’์„ ๋นผ์•ผํ•˜๋ฉด ์ตœ์†Œํž™์—์„œ remove๋ฅผ ํ•ด์ฃผ๊ณ  ์ตœ๋Œ€ํž™์—์„œ pop์„ ํ•ด์ค€๋‹ค. 

 

๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๊ฐ€ ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•˜์ง€ ์•Š๊ณ  heapq.nsmallest / heaqp.nlargest ๋ผ๋Š” ๊ฒƒ์ด ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ์•˜๋‹ค. 

์ด๊ฑธ ์‚ฌ์šฉํ•˜๋ฉด ๊ตณ์ด ์ตœ๋Œ€/์ตœ์†Œ ํž™์„ ๊ตฌํ˜„ํ•˜์ง€ ์•Š์•„๋„ ๋ฌธ์ œ ํ•ด๊ฒฐ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. 

heap = heapq.nlargest(len(heap), heap)[1:]
heapq.heapify(heap)