zoukankan      html  css  js  c++  java
  • LeetCode "Sliding Window Maximum"

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

    Typical Solution: element in array will be pushedpopped infrom 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;
        }
    };
  • 相关阅读:
    322. Coin Change
    368.[LeetCode] Largest Divisible Subset
    c++
    python 循环
    2018今日头条
    c++中set的用法
    [LeetCode]48. Rotate Image 旋转图片
    [LeetCode]47. Permutations II
    [LeetCode]46. Permutations
    sys与os模块(转载)
  • 原文地址:https://www.cnblogs.com/tonix/p/4660878.html
Copyright © 2011-2022 走看看