有一个整型数组arr和一个大小为w的窗口从数组的最左边滑到最右边,窗口每次向右边滑一个位置,求每一种窗口状态下的最大值。(如果数组长度为n,窗口大小为w,则一共产生n-w+1个窗口的最大值)
第一行输入n和w,分别代表数组长度和窗口大小第二行输入n个整数,表示数组中的各个元素
输出一个长度为n-w+1的数组res,res[i]表示每一种窗口状态下的最大值
8 3 4 3 5 4 3 3 6 7
5 5 5 4 6 7
例如,数组为[4,3,5,4,3,3,6,7],窗口大小为3时:
[4 3 5] 4 3 3 6 7 窗口中最大值为5
4 [3 5 4] 3 3 6 7 窗口中最大值为5
4 3 [5 4 3] 3 6 7 窗口中最大值为5
4 3 5 [4 3 3] 6 7 窗口中最大值为4
4 3 5 4 [3 3 6] 7 窗口中最大值为6
4 3 5 4 3 [3 6 7] 窗口中最大值为7
输出的结果为{5 5 5 4 6 7}
#include <stdio.h> #include <stdlib.h> typedef struct node { int val; struct node *prev; struct node *next; } Node; Node *createNode(int val); void addLast(int val); void removeFirst(); // the head and tail of the double-ended queue Node *pHead = NULL; Node *pTail = NULL; int main(void) { int n, w; scanf("%d%d", &n, &w); int *arr = (int *) malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { scanf("%d", arr + i); } int l = 0, r = 0; while (r < w) { addLast(arr[r++]); } int index = 0; int *res = (int *) malloc((n - w + 1) * sizeof(int)); for (;;) { res[index++] = pHead->val; if (arr[l++] == pHead->val) removeFirst(); if (r == n) break; addLast(arr[r++]); } // print result for (int i = 0; i < index; i++) { printf("%d ", res[i]); } // release memory while (pHead != NULL) removeFirst(); free(arr); free(res); return 0; } Node *createNode(int val) { Node *node = (Node *) malloc(sizeof(Node)); node->val = val; node->prev = NULL; node->next = NULL; return node; } void addLast(int val) { Node *pNode = NULL; while (pHead != NULL && val > pTail->val) { pNode = pTail; if (pHead == pTail) { pHead = NULL; pTail = NULL; } else { pTail = pTail->prev; pTail->next = NULL; } free(pNode); } pNode = createNode(val); if (NULL == pHead) { pHead = pNode; pTail = pNode; return; } pTail->next = pNode; pNode->prev = pTail; pTail = pNode; } void removeFirst() { Node *pNode = pHead; if (pHead == pTail) { pHead = NULL; pTail = NULL; } else { pHead->next->prev = NULL; pHead = pHead->next; } free(pNode); }