Authored by Tony Feng
Created on May 8th, 2022
Last Modified on May 8th, 2022
Task 1 - Q59,I. 滑动窗口的最大值
Question
给定一个数组 nums
和滑动窗口的大小 k
,请找出所有滑动窗口里的最大值。你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。
1
2
3
4
5
6
7
8
9
10
11
12
|
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
|
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
ans, window = [], [] # Record the indices whose nums are in descending order
for i in range(len(nums)):
# Remove the index whose elements < the new num
while window and nums[i] > nums[window[-1]]:
window.pop()
# Add the index of the new num
window.append(i)
# if the size of the window > k, pop the first index in the window
if i - window[0] + 1 > k:
window.pop(0)
# Add the first element after the window is formed
if i >= k - 1:
ans.append(nums[window[0]])
return ans
|
Explanation
- Time Complexity: O(N)
- Space Complexity: O(K), i.e. It depends on the k
Task 2 - Q59,II. 队列的最大值
Question
请定义一个队列并实现函数 max_value
得到队列里的最大值,要求函数max_value
、push_back
和 pop_front
的均摊时间复杂度都是O(1)
。若队列为空,pop_front
和 max_value
需要返回 -1
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import queue
class MaxQueue:
def __init__(self):
self.queue = queue.Queue()
self.deque = queue.deque() # Double-ended queue, the left is always the largest
def max_value(self) -> int:
return self.deque[0] if self.deque else -1
def push_back(self, value: int) -> None:
self.queue.put(value)
while self.deque and self.deque[-1] < value:
self.deque.pop()
self.deque.append(value)
def pop_front(self) -> int:
if self.queue.empty():
return -1
val = self.queue.get()
if val == self.deque[0]:
self.deque.popleft()
return val
|
Explanation
- Time Complexity
max_value
: O(1)
pop_front
: O(1)
push_back
: O(1)
- For example, 543216,the last
push_back
takes O(N) and the rest of each only needs O(1). So the average is (O(1)*(N-1)+O(N))/N=O(1).
- Space Complexity: O(N)