-
Notifications
You must be signed in to change notification settings - Fork 17
/
sliding-window-maximum.py
74 lines (50 loc) · 1.79 KB
/
sliding-window-maximum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import heapq
from collections import deque
from typing import Deque, List, Set, Tuple
class Heap:
def __init__(self) -> None:
self.heap: List[Tuple[int, int]] = []
self.present: Set[Tuple[int, int]] = set()
def push(self, value: Tuple[int, int]) -> None:
heapq.heappush(self.heap, value)
self.present.add(value)
def pop(self) -> Tuple[int, int]:
self.peek()
return heapq.heappop(self.heap)
def peek(self) -> Tuple[int, int]:
while self.heap[0] not in self.present:
heapq.heappop(self.heap)
return self.heap[0]
def discard(self, value: Tuple[int, int]) -> None:
self.present.discard(value)
class Solution:
def maxSlidingWindowHeap(self, nums: List[int], k: int) -> List[int]:
result: List[int] = []
heap = Heap()
for pos in range(k):
heap.push((-nums[pos], pos))
if heap:
result.append(-heap.peek()[0])
for pos in range(k, len(nums)):
heap.discard((-nums[pos - k], pos - k))
heap.push((-nums[pos], pos))
result.append(-heap.peek()[0])
return result
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
queue: Deque[int] = deque()
def add(pos: int) -> None:
while queue and nums[queue[-1]] <= nums[pos]:
queue.pop()
queue.append(pos)
def discard_left(pos: int) -> None:
if queue[0] == pos:
queue.popleft()
result: List[int] = []
for pos in range(k):
add(pos)
result.append(nums[queue[0]])
for pos in range(k, len(nums)):
discard_left(pos - k)
add(pos)
result.append(nums[queue[0]])
return result