https://leetcode.com/problems/sliding-window-maximum/description/
from typing import List
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
window = deque(nums[:k], maxlen=k)
answer = [max(window)]
for num in nums[k:]:
window.append(num)
answer.append(max(window))
return answer
from typing import List
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
window = deque()
max_v = nums[0]
answer = []
for idx, num in enumerate(nums):
window.append(num)
# set first window
if idx < k - 1:
if num >= max_v:
max_v = num
continue
# update max_v
if max_v is None:
max_v = num
for i in range(k):
if nums[idx - i] > max_v:
max_v = nums[idx - i]
elif num >= max_v:
max_v = num
answer.append(max_v)
# pop max value, set max value
if max_v == window.popleft():
max_v = None
return answer
책에 나와 있는 풀이를 참고하여 최적화를 해봤지만 시간 초과를 해결하지 못하였다.
from typing import List
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
result = []
window = deque()
for i, num in enumerate(nums):
# step 1
while window and window[0] < i - k + 1:
window.popleft()
# step 2
while window and nums[window[-1]] < num:
window.pop()
# step 3
window.append(i)
# step 4
if i >= k - 1:
result.append(nums[window[0]])
return result
파이썬 알고리즘 인터뷰 75번