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.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
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
Therefore, return the max sliding window as [3,3,5,5,6,7].
[分析] 首先要正确理解题意,结果是返回每个长度为k的窗口中的最大值。当窗口滑动一格时如何确定窗口中的最大值呢?直接的方法是遍历,则复杂度是O(k * n),选用最大堆存储窗口,则找到当前堆中最大值时O(1),窗口滑动时,需要添加一个新元素并删除窗口左边界元素,耗费为O(logk),因此总的复杂度是O(n*logk),当k很大时效率提升比较明显
更优的思路是使用Deque, 时间复杂度为O(N),之前都没用过这种数据结构,JDK文档上说ArrayDeque用作stack时比Stack数据结构快,用作queue时比LinkedList快,好东西呀~
参考
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
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
Therefore, return the max sliding window as [3,3,5,5,6,7].
[分析] 首先要正确理解题意,结果是返回每个长度为k的窗口中的最大值。当窗口滑动一格时如何确定窗口中的最大值呢?直接的方法是遍历,则复杂度是O(k * n),选用最大堆存储窗口,则找到当前堆中最大值时O(1),窗口滑动时,需要添加一个新元素并删除窗口左边界元素,耗费为O(logk),因此总的复杂度是O(n*logk),当k很大时效率提升比较明显
更优的思路是使用Deque, 时间复杂度为O(N),之前都没用过这种数据结构,JDK文档上说ArrayDeque用作stack时比Stack数据结构快,用作queue时比LinkedList快,好东西呀~
参考
https://leetcode.com/discuss/46578/java-o-n-solution-using-deque-with-explanation
// Method 2: O(N), using Deque
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length == 0)
return new int[0];
int n = nums.length;
int[] max = new int[n - k + 1];
int idx = 0;
Deque<Integer> deque = new ArrayDeque<Integer>();
for (int i = 0; i < n; i++) {
if (!deque.isEmpty() && deque.peek() == i - k)
deque.pollFirst();
while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i])
deque.pollLast();
deque.offer(i);
if (i >= k - 1) max[idx++] = nums[deque.peek()];
}
return max;
}
// Method 1: O(N * logk), using PriorityQueue
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null)
return null;
if (nums.length == 0)
return new int[0];
int n = nums.length;
int[] result = new int[n - k + 1];
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new LargerComparator());
for (int i = 0; i < k; i++) {
maxHeap.offer(nums[i]);
}
result[0] = maxHeap.peek();
int start = 0;
for (int i = k; i < n; i++) {
maxHeap.offer(nums[i]);
maxHeap.remove(nums[start++]);
result[i - k + 1] = maxHeap.peek();
}
return result;
}
}
class LargerComparator implements Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}