The maximum value of the sliding window to prove safety offer

Title Description

Given an array and the size of the sliding window, sliding window to find the maximum value among all values. For example, if the input array size and {2,3,4,2,6,2,5,1} 3 sliding window, then the presence of a total of six sliding window, their maximum values ​​is {4,4,6, 6,6,5}; it has the following six array {2,3,4,2,6,2,5,1} for the sliding window: {[2,3,4], 2,6,2,5 , 1}, {2, [3,4,2], 6,2,5,1}, {2,3, [4,2,6], 2, 5}, {2,3,4 , [2,6,2], 5,1}, {2,3,4,2, [6,2,5], 1}, {2,3,4,2,6, [2,5, 1]}.

Thinking

  1. Violence Solution: through each window, the maximum value saved to the res, the final output can be
  2. Optimization Method: sliding window should be a queue, in order to obtain the maximum value of the sliding window, the queue elements from both ends of the sequence may be deleted, so use deque.
    Principle: k for the new element, with which the elements deque comparison
    1) of the front is smaller than k, is directly removed from the queue (it is no longer likely to be the maximum value of the sliding window behind),!
    2) in front of X is larger than k, comparing the two subscripts, X is determined whether or not within the window, gone directly dequeued
    first element of the queue is the maximum value in the sliding window

Code

Violence Solution:

class Solution {
public:
    vector<int> maxInWindows(const vector<int>& num, unsigned int size)
    {
        
        vector<int> res;
        if(num.size() == 0 || size < 1)
            return res;
        int i = 0;
        if(num.size() < size)
        {
            return res;
        }
        for(i = 0; i < num.size()-size+1;i++)
        {
            vector<int> tmp;
            for(int j = i;j < i + size;j++)
            {
                tmp.push_back(num[j]);
            }
            sort(tmp.begin(),tmp.end());
            res.push_back(tmp[tmp.size()-1]);
        }
        return res;
    }
};

Optimization Solution:

链接:https://www.nowcoder.com/questionTerminal/1624bc35a45c42c0bc17d17fa0cba788?f=discussion
来源:牛客网

//引用马客(Mark)的解题思路,马客没加注释,我用自己的理解加下注释,希望对你们有用,
//如有错误,见谅,我会及时修改。
//deque s中存储的是num的下标
class Solution {
public:
    vector<int> maxInWindows(const vector<int>& num, unsigned int size)
    {
        vector<int> res;
        deque<int> s;
        for(unsigned int i=0;i<num.size();++i){
            while(s.size() && num[s.back()]<=num[i])//从后面依次弹出队列中比当前num值小的元素,同时也能保证队列首元素为当前窗口最大值下标
                s.pop_back();
            while(s.size() && i-s.front()+1>size)//当当前窗口移出队首元素所在的位置,即队首元素坐标对应的num不在窗口中,需要弹出
                s.pop_front();
            s.push_back(i);//把每次滑动的num下标加入队列
            if(size&&i+1>=size)//当滑动窗口首地址i大于等于size时才开始写入窗口最大值
                res.push_back(num[s.front()]);
        }
        return res;
    }
};
Published 85 original articles · won praise 0 · Views 392

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/104885748