스택은 잘 쓰겠는데 큐는 잘 못쓰겠다
그래서 공부도 할 겸 올리는 포스트
이번에 푼 문제는 프로그래머스 Lv2.프린터
중요도 순서대로 출력하고 매개변수로 넘긴 위치의 출력 순서를 리턴하는 문제이다
나는 처음에 리스트로만 풀려고 하니까 계속 꼬여서...
양방향 큐, 앞 뒤에서 추가하거나 삭제할 수 있다
일반적 리스트는 추가 삭제 연산에 O(n)인데 데크는 O(1)
from collections import deque
deq = deque() #생성
#-
#
#_
deq.append('a') #끝에 넣어줌
#-
#a
#_
deq.appendleft('b') #처음부분에 넣어줌
#- -
#b a
#_ _
deq.appendleft('c') #처음부분에 넣어줌
#- - -
#c b a
#_ _ _
deq.pop() #끝에꺼 삭제
#- -
#c b
#_ _
deq.popleft() #처음꺼 삭제
# -
# b
# _
deq.remove('b') #b찾아 삭제
deq.rotate(1) #데크를 num만큼 회전 (양수면 오른쪽)
print(deq)
# deque([5, 1, 2, 3, 4])
deq.rotate(-1) #음수면 왼쪽
print(deq)
# deque([1, 2, 3, 4, 5])
def solution(priorities, location):
queue = [(i,p) for i,p in enumerate(priorities)]
answer = 0
while True:
cur = queue.pop(0)
print(queue)
if any(cur[1] < q[1] for q in queue):
queue.append(cur)
print(queue)
else:
answer += 1
if cur[0] == location:
return answer
solution([1, 1, 9, 1, 1, 1], 0)