Skip to content

Commit

Permalink
leetcode/python/hard/239_sliding_window_maximum.py
Browse files Browse the repository at this point in the history
  • Loading branch information
bong6981 committed Sep 9, 2022
1 parent fb4d2a4 commit 2d84559
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions leetcode/python/hard/239_sliding_window_maximum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import collections
import sys, heapq

## heapq를 이용한 풀이
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
heap = []
answer = []
for i, v in enumerate(nums):
heapq.heappush(heap, (-v, i))
if i < k -1:
continue
while(heap and heap[0][1] <= (i - k)):
heapq.heappop(heap)
answer.append(-heap[0][0])
return answer

## deque를 이용한 풀이
def maxSlidingWindow(nums, k):
q = collections.deque()
ans = []
for i, v in enumerate(nums):
if q and q[0] == i - k:
q.popleft()

while q:
if nums[q[-1]] < v:
q.pop()
else:
break

q.append(i)
if i >= k - 1:
ans.append(nums[q[0]])
return ans

0 comments on commit 2d84559

Please sign in to comment.