Hello World!

프로그래머스 - 이중순위큐,k 번째 수

by PyTong

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

 

내 코드를 잃어 버렸다, 하지만 쉽다

 

 

 

 

 

블로그의 정보

PyTong

PyTong

활동하기