본문 바로가기

computer science/algorithm

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

<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=' ')

'computer science > algorithm' 카테고리의 다른 글

sorted, sort()  (1) 2024.01.29
[boj 11725] 트리의 부모 찾기  (0) 2024.01.11
Greedy (그리디, 탐욕 알고리즘)  (0) 2023.12.12
sorting (정렬)  (1) 2023.11.28
Dynamic Programming (동적 계획법)  (1) 2023.11.24