Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2015-07-20 11:08  Tonix  阅读(434)  评论(0编辑  收藏  举报