프로그래머스
[프로그래머스]프린터
daniel7481
2022. 7. 21. 16:17
반응형
https://school.programmers.co.kr/learn/courses/30/lessons/42587
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
간단한 레벨2 힙 문제이다. 사실 자료구조 문제라고 해야하는게 힙 자료구조와 큐를 사용하였다. 먼저 우선순위를 최대 힙으로 작은 순으로 만들어주고, 큐에 내가 원하는 문서의 인덱스가 나올때 참 값을 가지게 하는 리스트를 원소로 넣어주었다. 그 다음 큐를 탐색하면서 flag가 참값이 나오고, 최대 힙의 첫 번쨰 요소보다 우선순위(n)이 높다면 cnt를 answer에 할당해주었다.
import heapq
from collections import deque
def solution(priorities, location):
answer = 0
max_heap = []
for i in range(len(priorities)):
heapq.heappush(max_heap, [-priorities[i], priorities[i]])
q = deque()
for i in range(len(priorities)):
if i == location:
q.append([priorities[i], True])
else:
q.append([priorities[i], False])
cnt = 0
while q:
n, flag = q.popleft()
#print(n, flag)
if n < max_heap[0][1]:
q.append([n, flag])
else:
cnt += 1
if flag:
answer = cnt
break
heapq.heappop(max_heap)
return answer반응형