Problem
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[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
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
Solution
using max heap O(nlogn)
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<>((i1, i2)->i2-i1);
if (nums == null || k == 0 || nums.length < k) return new int[0];
int[] res = new int[nums.length-k+1];
for (int i = 0; i < k; i++) queue.offer(nums[i]);
res[0] = queue.peek();
for (int i = k; i < nums.length; i++) {
queue.remove(nums[i-k]);
queue.offer(nums[i]);
res[i-k+1] = queue.peek();
}
return res;
}
}
using Deque to maintain a window O(n)
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || k == 0 || nums.length < k) return new int[0];
int[] res = new int[nums.length-k+1];
int index = 0;
Deque<Integer> queue = new ArrayDeque<>(); //queue to save index
for (int i = 0; i < nums.length; i++) {
//丢弃队首那些超出窗口长度的元素 index < i-k+1
if (!queue.isEmpty() && queue.peek() < i-k+1) queue.poll();
//队首的元素都是比后来加入元素大的元素,所以存储的index对应的元素是从小到大
while (!queue.isEmpty() && nums[queue.peekLast()] < nums[i]) queue.pollLast();
queue.offer(i);
if (i >= k-1) res[index++] = nums[queue.peek()];
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。