-
Notifications
You must be signed in to change notification settings - Fork 328
Open
Description
교재의 "75. 최대 슬라이딩 윈도우" 문제 관련 이슈 남깁니다.
1) (571~574쪽) "75. 최대 슬라이딩 윈도우" 문제 풀이 부분
교재의 풀이 1, 풀이 2 모두 time out error 가 납니다.
각 window 마다 max를 매번 계산하는 부분 때문으로 보입니다.
test case의 nums 리스트가 100,000개, k가 50,000개일 경우,
교재의 풀이방식은 100,000*50,000 이므로 50억으로 시간초과가 납니다.
그래서 deque를 이용해서 O(n)으로 풀었더니 1492 ms로 전체 풀케이스를 통과할 수 있었습니다.
from collections import deque
from typing import List
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
deq, ans = deque(), []
for i in range(len(nums)):
# 앞에서부터 out of window -> 제거
if deq and i-deq[0] == k:
deq.popleft()
# 뒤에서부터 현재 추가할 숫자보다 작으면 -> 제거 (deq에 불필요한 숫자 없도록!)
while deq and nums[deq[-1]] <= nums[i]:
deq.pop()
deq.append(i) # 현재 숫자 추가( (i, num[i])로 저장해도 되나, 숫자 위치 저장만 해 space 줄임)
# 출력 부분 (현재 위치 >= window size일 때)
if i+1 >= k:
ans.append(nums[deq[0]]) # 맨 앞은 현재 window 에서 가장 큰 수
return ans
sol = Solution()
print(sol.maxSlidingWindow(nums=[1,3,-1,-3,5,3,6,7], k=3))
2) (572쪽) 시간복잡도 서술 부분
-"매번 윈도우의 최댓값을 계산하기 때문에 이 경우 시간 복잡도는 O(n)이다."
K의 크기에 영향을 받으므로, O(N*K)가 더 정확할 것 같습니다.
MoonHyuk, pythaac, inyong37, jxxxxe, Bleron97 and 10 morekizarrd and okayhooni
Metadata
Metadata
Assignees
Labels
No labels