computer science/algorithm

큐에 (), []로 추가할 때의 시간 차이

nani-jin 2024. 1. 16. 12:38

<boj 11003 : 최솟값 찾기> 문제를 데크를 이용해 푸는데,

요소를 [A[i],i]로 추가하면 시간 초과가 나고 (A[i],i)로 추가하면 시간 내로 정답이 떴다

 

아직 이유를 못 찾아서 남겨둠!

# [A[i],i]로 시간 초과
from collections import deque
import sys
input = sys.stdin.readline

n,l = map(int,input().split())
A = list(map(int,input().split()))
q = deque()

for i in range(n):
    while q and q[-1][0] > A[i]:
        q.pop()
        
    q.append([A[i],i])
    
    if q[-1][1] - q[0][1] >= l:
        q.popleft()

    print(q[0][0],end=' ')

 

# (A[i],i)로 시간 내에 정답
from collections import deque
import sys
input = sys.stdin.readline

n,l = map(int,input().split())
A = list(map(int,input().split()))
q = deque()

for i in range(n):
    while q and q[-1][0] > A[i]:
        q.pop()
        
    q.append((A[i],i))
    
    if q[-1][1] - q[0][1] >= l:
        q.popleft()

    print(q[0][0],end=' ')