Find the maximum value of the sliding window

topic:

Given a set of sequences and a sliding window size, find the maximum value in the sliding window. For example, given the sequence 2, 3, 4, 2, 10, 8, 12 and a window size of 3, the sliding window maximum is 4, 4, 10, 10, 12.

analyze:

  1. Brute-force method: the number of input sequences is n, and the window size is k. Scan the sliding window in turn to find its maximum value. Obviously, the time complexity of this algorithm is O(n*k) in the worst case.
  2. How to reduce the time complexity to O(n), which requires that the time complexity of finding the maximum value in the window every time is O(1). For this method, please refer to the sword offer.
/* 滑动窗口的最大值
 * 时间复杂度O(nk), 为元素个数, k为窗口大小
 */
#include <iostream>
using namespace std;
int find_max(int a[], int p, int r)
{
    int max_index = 0;
    for(int i = p; i <= r; i++){
        if(a[max_index] < a[i])
            max_index = i;
    }
    return max_index;
}

void window(int a[], int n, int size)
{
    int max_index = 0;
    int *max = new int[n-size+1];
    int j = 0;

    max_index = find_max(a, 0, size-1);
    max[j++] = a[max_index];
    for(int i = size; i < n; i++){
        if(max_index > i-size && a[max_index] < a[i])
            max_index = i;
        if(max_index <= i-size)
            max_index = find_max(a, i-size+1 , i);

        max[j++] = a[max_index];
    }
    delete[] max;
}

int main()
{
    //int a[] = {2,3,4,2,6,2,5,1};
    int a[] = {2,11,4,10,6,2,5,1,100,99,10};
    window(a, sizeof(a)/sizeof(int), 3);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325715180&siteId=291194637