239. Sliding Window Maximum
naive
T: O(nk), sliding windows
in each k size window,
find max value(when right - left + 1 == k), do n times
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (k == 1) {
return nums;
}
int result[] = new int[nums.length - k + 1];
int left = 0;
for (int right = 0; right < nums.length; right++) {
if (right - left + 1 == k) {
int max = Integer.MIN_VALUE; // in size k window find local max
for (int i = left; i <= right; i++) {
max = Math.max(max, nums[i]);
}
result[left++] = max;
}
}
return result;
}
}or left don't move, right move, also T: O(nk)
Heap
之後再來寫看看
dequeue
use deque to store index,
peek() = peekFirst()
poll() = pollFirst()
offer() = offerLast()
Q. how many result?
A. (n-k+1)
0. use deque to save index, so...
check range: peek() < (i - k +1)
i-k+1就是維持 k個 sliding windows, 超出就poll(pollFront
k = 3
i 0 1 2 3, i = 3, 3-3+1 = 1, so 小於 1 的 index 都丟掉
new coming value is bigger than peekLast() (last roud latest), discard last,
(因為新的都加在尾端, 如果新來得值比last大, discard last in dq
offer new coming value index (offer: offerLast()
add result
O(n)
[1, 3, - 1], 3, .....
idx = 2,
2 -3 +1 = 0, 這時候才出現第一組答案
dequeue new version
T:O(n), while loop < n, so can ignore
S: O(n), since O(n−k+1) is used for an output array and O(k) for a deque.
if 3 poll first, it's wrong, this max can remain for next to use,
unless , this time we poll the number is the max one, abandon it

more structure way
and offer number, not index
Last updated
Was this helpful?