[Leetcode] 239. Sliding Window Maximum 解题报告

来源:互联网 发布:哪个软件收视率准 编辑:程序博客网 时间:2024/05/17 16:03

题目

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

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?

思路

1、利用大顶堆:我们知道大顶堆可以保证最开始的元素是最大的,所以在本题目中,我们维护一个大顶堆。每遍历到一个数,首先调整大顶堆,使得开头元素最大,然后判断最大值知否还在k窗口之内,如果不在,就迭代删除,直到最大元素仍然在k窗口之内。如果窗口大小已经达到了k,就添加当前的最大元素到结果集中。由于调整大顶堆的时间复杂度是O(logn),所以本算法的时间复杂度是O(nlogn)。

2、利用双边队列:还有一种更巧妙的解法就是利用双边队列。我们在双边队列中维护一个递减序列,也就是说,当遍历到一个新数之后,我们从双边队列的尾部开始,删除所有小于等于它的数,然后将该数加入到双边队列的尾部。这种处理方法可以保证双边队列中的数一定是单调递减的,当前最大数一定位于双边队列的首位。这样当窗口足够大的时候,我们直接将队列首位元素加入结果集中即可。当然在遍历的过程中,不要忘了更新队列。在代码实现中,为了方便更新队列,我们在双边队列中存储的是最大数的在数组中的索引,而不是具体值。该算法的时间复杂度是O(n)。在分析的过程中我们发现,虽然在for循环内部还有while循环,但是采用均摊分析可知,数组中的每个数最多入队列一次,出队列一次。

代码

1、利用大顶堆:

class Solution {public:    vector<int> maxSlidingWindow(vector<int>& nums, int k) {        vector<pair<int, int>> windows;        vector<int> ret;        for(int i = 0; i < nums.size(); ++i) {            windows.push_back(make_pair(nums[i], i));            push_heap(windows.begin(), windows.end());            while(i - windows[0].second >= k) {                pop_heap(windows.begin(), windows.end());                windows.pop_back();            }            if(i + 1 >= k) {                ret.push_back(windows[0].first);            }        }        return ret;    }};

2、利用双边队列:

class Solution {public:    vector<int> maxSlidingWindow(vector<int>& nums, int k) {        vector<int> ret;        if(nums.size() == 0 || k == 0) {            return ret;        }        deque<int> que;     // only stores the indices        for(int i = 0; i < nums.size(); ++i) {            while(!que.empty() && nums[i] >= nums[que.back()]) {                que.pop_back();            }            que.push_back(i);            if(i >= que.front() + k) {                que.pop_front();            }            if(i >= k - 1) {                ret.push_back(nums[que.front()]);            }        }        return ret;    }};

原创粉丝点击