Record a pair of questions that are similar but completely different, but each has its merits. 239. Sliding window maximum value-->ali find the maximum value in every k

Three, 239. Sliding window maximum value --->ali Find the maximum value of each k

3.1  239. Maximum sliding window

A monotonic two-way queue is used . This data structure can push/pop elements from both ends in a constant time .
It is more convenient to store the index of a double queue than to store the elements, because both can be used in array analysis.
The algorithm is very straightforward:
process the first k elements and initialize the two-way queue.
Traverse the entire array. At each step:
Clean up the two-way queue:
  -Only keep the index of the element in the current sliding window. //pop_front()
  -Remove all elements smaller than the current element, they cannot be the largest. //pop_back()
adds the current element to the two-way queue.
Add deque[0] to the output. //Because it is a monotonic queue, the head of the queue must be the largest.
Return the output array.

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        deque<int> dq;//单调双端队列
        vector<int> ans;
        int len=0;
        for (int i=0;i<nums.size();++i)
        {
            while (len>0 && (i-dq[0]>=k)) 
            {
                dq.pop_fron

Guess you like

Origin blog.csdn.net/hbhhhxs/article/details/108149687