# FireEmissary

C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
 14 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks

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         31 [3  -1  -3] 5  3  6  7          31  3 [-1  -3  5] 3  6  7          51  3  -1 [-3  5  3] 6  7          51  3  -1  -3 [5  3  6] 7          61  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, 1 ≤ k ≤ input array's size.

Could you solve it in linear time?

Hint:

1. How about using a data structure such as deque (double-ended queue)?
2. The queue size need not be the same as the window’s size.
3. Remove redundant elements and the queue should store only elements that need to be considered.

vector<int> maxSlidingWindow(vector<int>& nums, int k) {

if(nums.size()<2)return nums;
size_t n
=nums.size(), maxv=0,secondv=~0;
vector
<int> out;

//secondv维持第二大的元素.如果maxv在窗口边界，secondv就是魔术~0代表不存在第二小元素.
for(size_t i=1;i<k;++i)
{

if(nums[i]>nums[maxv]){
maxv
=i;
secondv
=~0;
}
else  if(secondv==~0||nums[i]>nums[secondv]){
secondv
=i;
}
}

out.push_back(nums[maxv]);

for(size_t i=k;i<n;++i)
{

if(maxv<=i-k)
{

if(secondv==~0){
maxv
=i;
}
else{
maxv
=secondv;
secondv
=secondv+1;

//maxv移出滑动窗口时，如果secondv存在，显然要更新它找出新的第二大元素.
for(size_t j=secondv+1;j<i;++j)

if(nums[j]>nums[secondv])secondv=j;
}
}

if(nums[i]>nums[maxv]){
maxv
=i;
secondv
=~0;
}
else  if(secondv==~0||nums[i]>nums[secondv]){
secondv
=i;
}

out.push_back(nums[maxv]);

}

return out;
}

posted on 2016-07-24 14:54 FireEmissary 阅读(659) 评论(0)  编辑 收藏 引用