码迷,mamicode.com
首页 > Windows程序 > 详细

leetcode - Sliding Window Maximum

时间:2015-07-18 14:13:27      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:c++   程序员   面试   

题目:

Sliding Window Maximum

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, 1 ≤ k ≤ input array‘s size.

Follow up:
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.

分析:

用一个双向队列d保存窗口信息,队列中的元素是非递增的(即相邻严肃要么相等要么递减),队列的元素个数不超过窗口大小,队列的d.front()是当前窗口的最大值。


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




版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode - Sliding Window Maximum

标签:c++   程序员   面试   

原文地址:http://blog.csdn.net/bupt8846/article/details/46941421

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!