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

LeetCode "Sliding Window Maximum"

时间:2015-07-20 12:27:54      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

Monotonic Queue is getting more popular, and finally LeetCode put it on.

Typical Solution: element in array will be pushed\popped in\from a sorted data structure, which points to multiset(or any heap-like data structure). Complexity is O(nlgn).

But with Monotonic Queue, we can solve it in O(n). http://abitofcs.blogspot.com/2014/11/data-structure-sliding-window-minimum.html

Lesson learnt: Monotonic Queue drops elements..

class Solution 
{
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) 
    {    
        vector<int> ret;
        if (k == 0) return ret;
        if (k == nums.size())
        {
            ret.push_back(*std::max_element(nums.begin(), nums.end()));
            return ret;
        }
        deque<int> mq; // only store index
        for (int i = 0; i < nums.size(); i++)
        {
            if (!mq.empty() && mq.front() <= i - k)
                mq.pop_front();
            while (!mq.empty() && nums[mq.back()] < nums[i])
                mq.pop_back();
            mq.push_back(i);
            if (i >= k - 1) ret.push_back(nums[mq.front()]);
        }
        return ret;
    }
};

LeetCode "Sliding Window Maximum"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4660878.html

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