leetcode No239. Sliding Window Maximum

来源:互联网 发布:网络系统安全课程 编辑:程序博客网 时间:2024/05/01 01:31

Question:

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.

Algorithm:

用双向队列来解决问题
Ex:1 3 -1 -3 5 3 6 7     size=3
1、因为此时队列为空,在队尾插入1
back        1(下标0)           front
2、因为3比1大,所以1不可能是最大的元素,所以把1删除,pop_back(),并在队尾插入1
back        3(下标1)          front
3、-1比3小,如果3删除后,-1可能是最大的元素,所以在队尾插入-1
back       -1(下标2)     3(下标1)    front
4、-3比-1小,所以在队尾插入-3
back       -3(下标3)     -1(下标2)    3(下标1)   front
5、5比-3、-1、3都大,所以-3、-1、3删除,并在队尾插入5
back       5(下标4)      front
6、3比5小,在队尾插入3
back      3(下标5)     5(下标4)    front
7、6比3、5大,删除3、5,在队尾插入6
back      6(下标6)       front
8、7比6大,删除6、在队尾插入7
back      7      front
注意:如果此时的滑动窗口不包括队头元素了,要把队头元素删除
判断滑动窗口是否包含一个数字,应该在队列里存入数字在数组里的下标,而不是数值。但一个数字的下标与当前处理的数字的下标之差大于等于size时,这个数字可以从队列里删除

Accepted Code:

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



0 0
原创粉丝点击