- leetcode: Sliding Window Maximum | LeetCode OJ
- lintcode: (362) Sliding Window Maximum
Given an array of n integer with duplicate number, and a moving window(size k),
move the window at each iteration from the start of the array,
find the maximum number inside the window at each moving.
Example
For array [1, 2, 7, 7, 8], moving window size k = 3. return [7, 7, 8]
At first the window is at the start of the array like this
[|1, 2, 7| ,7, 8] , return the maximum 7;
then the window move one step forward.
[1, |2, 7 ,7|, 8], return the maximum 7;
then the window move one step forward again.
[1, 2, |7, 7, 8|], return the maximum 8;
Challenge
o(n) time and O(k) memory
问题来了,思路基本定型,现在就是选用合适的数据结构了。根据上面的思路,这种数据结构应该能在
public class Solution {
/**
* @param nums: A list of integers.
* @return: The maximum number inside the window at each moving.
*/
public ArrayList<Integer> maxSlidingWindow(int[] nums, int k) {
ArrayList<Integer> winMax = new ArrayList<Integer>();
if (nums == null || nums.length == 0 || k <= 0) return winMax;
int len = nums.length;
Deque<Integer> deque = new ArrayDeque<Integer>();
for (int i = 0; i < len; i++) {
// remove the smaller in the rear of queue
while ((!deque.isEmpty()) && (nums[i] > deque.peekLast())) {
deque.pollLast();
}
// push element in the rear of queue
deque.offer(nums[i]);
// remove invalid max
if (i + 1 > k && deque.peekFirst() == nums[i - k]) {
deque.pollFirst();
}
// add max in current window
if (i + 1 >= k) {
winMax.add(deque.peekFirst());
}
}
return winMax;
}
}
- 移除队尾元素时首先判断是否为空,因为在移除过程中可能会将队列元素清空。
- 在移除队尾元素时
nums[i] > deque.peekLast()
不可取等于号,因为这样会将相等的元素全部移除,这样会在窗口中部分元素相等时错误地移除本该添加到最终结果的元素。 - 移除失效元素和添加元素到最终结果时需要注意下标
i
和k
的关系,建议举例确定。
时间复杂度