LeetCode refers to Offer 59-I. Maximum sliding window

Link to the original question
Idea: Violent solution and deque.
Violent solution: every time the window moves, it searches for the maximum value in the current window.
Double-ended queue: store the subscript of the element, the corresponding element of the subscript in the queue is the order from large to small, and judge on time whether the maximum value in the current queue is still in the window.

Violent solution:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */


int maxInt(int* nums, int left, int numsSize){
    
    
    int max = -100000000;
    for(int i = 0; i < numsSize; i++){
    
    
        if(nums[left + i] > max) max = nums[left + i];
    }
    return max;
}

int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize){
    
    
    if(numsSize ==0 ){
    
    
        *returnSize = 0;
        return nums;
    }
    if(k == 1){
    
    
        *returnSize = numsSize;
        return nums;
    }
    *returnSize = numsSize - k + 1;
    int* arr = (int*)malloc(sizeof(int)*(numsSize - k + 1));
    for(int i = 0; i < numsSize - k + 1; i++){
    
    
        arr[i] = maxInt(nums, i, k);
    }
    return arr;
}

Deque:

class Solution {
    
    
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
    
    
        vector<int> res
        deque<int> tem;     
        for(int i=0; i<nums.size(); ++i)
        {
    
    
            while(!tem.empty() && nums[i]>nums[tem.back()]) tem.pop_back();
            if(!tem.empty() && tem.front()<i-k+1) tem.pop_front();
            tem.push_back(i);
            if(i>=k-1)  res.push_back(nums[tem.front()]);
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_43078427/article/details/111145679