239. Sliding Window Maximum解题报告

2017-12-26  本文已影响23人  黑山老水

Description:

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.
Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

Example:

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].

Link:

https://leetcode.com/problems/sliding-window-maximum/description/

解题方法:

如果我们能有一个维持descending的结构储存window里面的数字,那么这个问题就很容易解决。
max heap可以满足我们的需求,但是每次删除数字会额外耗费时间。
双向队列可以满足线性的要求,我们可以手动维护队列的顺序,当队尾的元素小于新来的元素,就pop_back,队头的元素维持当前窗口最大,当队头的元素不在窗口范围内,就pop_front。

为什么当队尾的元素小于最先来的元素可以直接pop而不是存下来接着排序呢?
因为我们已经有了比他们还要大的,新的元素到来,当这个新的元素没有过期时(在窗口范围内),那些需要pop的元素永远不可能成为最大的元素。当这个新的元素过期时,那些需要pop的元素都肯定过期。所以我们可以直接pop掉不用保留下来。

Tips:

Time Complexity:

O(N)

完整代码:

vector<int> maxSlidingWindow(vector<int>& nums, int k) {
    vector<int> result;
    deque<int> Q;
    for(int i = 0; i < nums.size(); i++) {
        while(!Q.empty() && i - k >= Q.front())
            Q.pop_front();
        while(!Q.empty() && nums[i] > nums[Q.back()])
            Q.pop_back();
        Q.push_back(i);
        if(i >= k - 1)
            result.push_back(nums[Q.front()]);
    }
    return result;
}
上一篇下一篇

猜你喜欢

热点阅读