Sliding Window Maximum 解答

Question

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

Solution

Key to the solution is to maintain a deque (size <= k) whose elements are always in descending order. Then, the first element is what we want.

Every time we want to add a new element, we need to check:

1. whether it is bigger than previous elements in deque.

If yes, we remove elements in deque which are smaller than current element.

2. whether the first element in deque is out of current sliding window.

If yes, we remove first element.

 public class Solution {

     public ArrayList<Integer> maxSlidingWindow(int[] nums, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
Deque<Integer> deque = new LinkedList<Integer>();
int i = 0;
for (int current : nums) {
i++;
// Ensure current deque is in decending order
while (!deque.isEmpty() && deque.peekLast() < current)
deque.pollLast();
deque.addLast(current);
if (i > k && deque.peekFirst() == nums[i - k - 1])
deque.pollFirst();
if (i >= k)
result.add(deque.peekFirst());
}
return result;
}
}
上一篇:解压缩框架--SSZipArchive


下一篇:Python的原型开发带来的关于Mock的思考