sliding window maximum

方法 操作 时间复杂度
method 1 暴力 for loop O(nk)
method 2 hashheap (sliding window median) getmax, delete, insert O(nlogk)
method 3 deque pop and push at front, pop at end O(n)

code

#include <list>
class Solution {
public:
    /**
     * @param nums: A list of integers.
     * @return: The maximum number inside the window at each moving.
     */

    void inqueue(list<int>& deque, int value)
    {
        while(!deque.empty() && deque.back() < value)
        {
            deque.pop_back();
        }
        deque.push_back(value);
    }

    void outqueue(list<int>& deque, int value)
    {
        if(deque.front() == value)
        {
            deque.pop_front();
        }
    }

    vector<int> maxSlidingWindow(vector<int> &nums, int k) {
        // write your code here
        vector<int> ret;
        list<int> deque;
        for(int i = 0; i<k-1; i++)
        {
            inqueue(deque, nums[i]);
        }

        for(int i = k-1; i<nums.size(); i++)
        {
            inqueue(deque, nums[i]);
            ret.push_back(deque.front());
            outqueue(deque, nums[i-k+1]);
        }

        return ret;
    }
};

results matching ""

    No results matching ""