[leetcode]239. Sliding Window Maximum

来源:互联网 发布:mac os 显示隐藏文件 编辑:程序博客网 时间:2024/06/07 09:51

题目链接:https://leetcode.com/problems/sliding-window-maximum/#/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 thek 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].

The basic idea is to use a deque (buffer) to save all currently potential "maximum" elements (i.e. the element in the current k-element window [i-k+1, i], and it is larger than the elements after itself). So for each i, we first pop up the elements that are no larger than nums[i] from buffer until we find one that is larger than nums[i] or the buffer is empty since those elements will be covered by nums[i] and can not be a maximum of any k-element window. Then we put nums[i] in the buffer. If i>=k-1, we need to ouput the maximum for window [i-k+1, i], which is the front element of buffer. At last, we will check if the front element is nums[i-k+1], if so, we have to pop it up since it will be out of the window [i-k+2, i+1] in the next iteration. Since all the elements will be pushed into/ popped out of the buffer only once, so the time complexity is O(N).

class Solution {public:    vector<int> maxSlidingWindow(vector<int>& nums, int k) {        deque<int> buffer;        vector<int> res;        for(auto i=0;i<nums.size();i++)        {            while(!dp.empty() && nums[i]>=nums[buffer.back()]) buffer.pop_back();            buffer.push_back(i);            if(i>=k-1) res.push_back(nums[buffer.front()]);            if(buffer.front()==i-k+1) buffer.pop_back();        }        return res;    }};



原创粉丝点击