๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป CS

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ด์ค‘์ˆœ์œ„ํ,k ๋ฒˆ์งธ ์ˆ˜

by dev.py 2022. 1. 21.

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

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ

 

programmers.co.kr

 

import heapq

class Double_heap:
    def __init__(self):     
        self.maxheap = list()
        self.minheap = list()
        
    
    def push(self, number):
        heapq.heappush(self.maxheap, -number)
        heapq.heappush(self.minheap, number)
    
    def pop_max(self):
        if self.maxheap and self.minheap :
            max_out = -heapq.heappop(self.maxheap)
            self.minheap.remove(max_out)
            heapq.heapify(self.minheap)

    def pop_min(self):
        if self.maxheap and self.minheap:
            min_out = heapq.heappop(self.minheap)
            self.maxheap.remove(-min_out)
            heapq.heapify(self.maxheap)
        
        
    def return_top(self):
        if self.minheap:
            top_min = heapq.heappop(self.minheap)
            top_max = -heapq.heappop(self.maxheap)
            return top_max, top_min
        else :
            return [0,0]
        
def solution(operations):
    
    doubleHeap = Double_heap()
    for operation in operations :
        if operation[0] == "I" :
            doubleHeap.push(int(operation[1:]))
        elif operation == "D -1" :
            doubleHeap.pop_min()
        elif operation == "D 1" :
            doubleHeap.pop_max()
        else :
            print("Error")
            return 
    

    answer = doubleHeap.return_top()
    return answer

์ด์ค‘ ์šฐ์„ ์ˆ˜์œ„ ํ๋ฅผ ๊ทธ๋ƒฅ ํž™ ๋‘๊ฐœ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ตฌํ˜„ํ–ˆ๋‹ค.

 

๋นˆ ํ์— ๋ฐ์ดํ„ฐ๋ฅผ ์‚ญ์ œํ•˜๋ผ๋Š” ์—ฐ์‚ฐ -> ๋ฌด์‹œ

 

" ์ด์ค‘ ์šฐ์„ ์ˆœ์œ„ ํ๊ฐ€ ํ•  ์—ฐ์‚ฐ operations๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ๋ชจ๋“  ์—ฐ์‚ฐ์„ ์ฒ˜๋ฆฌํ•œ ํ›„ ํ๊ฐ€ ๋น„์–ด์žˆ์œผ๋ฉด [0,0] ๋น„์–ด์žˆ์ง€ ์•Š์œผ๋ฉด [์ตœ๋Œ“๊ฐ’, ์ตœ์†Ÿ๊ฐ’]์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•ด์ฃผ์„ธ์š”  " -> ๋ง๋งŒ ์ž˜ ์ง€์ผœ์„œ ํ•˜์ž

 

๋ ˆ๋ฒจ 3์ด์ง€๋งŒ ์‰ฌ์šด ํŽธ์ธ๊ฑฐ ๊ฐ™๋‹ค.

 

https://programmers.co.kr/learn/courses/30/lessons/42748

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - K๋ฒˆ์งธ์ˆ˜

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

 

๋‚ด ์ฝ”๋“œ๋ฅผ ์žƒ์–ด ๋ฒ„๋ ธ๋‹ค, ํ•˜์ง€๋งŒ ์‰ฝ๋‹ค