Sliding Window Maximum

Description:

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:

class Solution {
public:
/**
* @param nums: A list of integers.
* @return: The maximum number inside the window at each moving.
*/
vector maxSlidingWindow(vector &nums, int k) {
vector rc;
auto sz = (int)nums.size();
if (k == 0 || sz < k) return rc;
deque ids;
for (int i = 0; i < sz; ++i) {
while (!ids.empty() && nums[ids.back()] < nums[i])
ids.pop_back();
ids.push_back(i);
while (ids.front() <= i-k)
ids.pop_front();
if (i >= k-1)
rc.push_back(nums[ids.front()]);
}
return rc;
}
};

posted @ 2015-10-12 02:20  影湛  阅读(158)  评论(0)    收藏  举报