[programmers] Heap - 이중우선순위큐
12536 단어 알고리즘heapprogrammersheap
문제 링크
문제 설명
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
I 숫자 큐에 주어진 숫자를 삽입합니다.
D 1 큐에서 최댓값을 삭제합니다.
D -1 큐에서 최솟값을 삭제합니다.
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
제한사항
- operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
- operations의 원소는 큐가 수행할 연산을 나타냅니다.
- 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 - 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
- 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
문제 풀이
시도 1
def solution(operations):
answer = []
for oper in operations:
print("oper: "+oper)
if oper[0] == "I":
num = int(oper[2:])
answer.append(num)
answer.sort()
print(answer)
elif len(answer) != 0:
if oper[2] == "-":
answer.pop(0)
print(answer)
else:
answer.pop()
print(answer)
if len(answer)==0:
return [0,0]
else:
return [answer[-1], answer[0]]
- push시 자동으로 최소힙을 생성하는 heapq를 사용하려고 했는데 사실 바로 갖다 heap 푸쉬하는게 아니었다. heap은 이진트리 기반이라 자식끼리의 대소, 즉 leaf노드의 정렬은 보장되지 않기 때문
- 분류는 힙인데 모르겠어서 걍 리스트에 넣고 소팅했다 통과는 됐지만 이러면 레벨3짜리 힙문제가 아니겠지?????
정답코드
import heapq
def solution(operations):
heap = []
for operation in operations:
operator, operand = operation.split(' ')
operand = int(operand)
if operator == 'I':
heapq.heappush(heap, operand)
elif heap:
if operand < 0:
heapq.heappop(heap)
else:
heap.remove(max(heap))
if not heap:
return [0, 0]
return [max(heap), heap[0]]
내코드
import heapq
def solution(operations):
answer = []
for oper in operations:
print("oper: "+oper)
if oper[0] == "I":
num = int(oper[2:])
heapq.heappush(answer, num)
print(answer)
elif len(answer) != 0:
if oper[2] == "-":
heapq.heappop(answer)
print(answer)
else:
answer.remove(max(answer))
print(answer)
if len(answer)==0:
return [0,0]
else:
return [answer[-1], answer[0]]
내꺼랑 다른게 없는거같은데 와 안되노 ,,,
→ 왜냐? heap에서 제일 끝 원소가 최대값이라고 보장할 수 없기 떄문,,,
return을 return [answer[-1], answer[0]]
이 아닌 return [max(answer), answer[0]]
로 해야함 ㅜ ㅜ
Author And Source
이 문제에 관하여([programmers] Heap - 이중우선순위큐), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@woo0_hooo/programmers-Heap-이중우선순위큐저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)