C语言求所有滑动窗口里数值的最大值-爱代码爱编程
题目:
代码:已编译通过,并测试,如有问题,请在下面留言。
#include <stdio.h>
#include <stdlib.h>
int get_windows(int *array, int array_length, int window_len){
int *assist_queue = NULL; //辅助队列
int head_pos, tail_pos;
int queue_len;
int i;
if(window_len > array_length || array_length <= 0 || window_len <= 0 || !array){
return -1;
}
//1. 初始化
assist_queue = calloc(sizeof(int), array_length);
if(!assist_queue) return -1;
head_pos = 0;
tail_pos = 0;
queue_len = 0;
//2. 查找
printf("[");
//i每加一次,窗口向前滑动一次
for(i = 0; i < array_length; i++){
if(queue_len > 0){
//超出窗口范围,则删除
if(assist_queue[head_pos] <= i - window_len){
head_pos += 1;
queue_len -= 1;
}
//从右向左删除列表中小于当前值的项
while(array[assist_queue[tail_pos - 1]] <= array[i] && tail_pos > head_pos){
tail_pos = tail_pos - 1;
queue_len = queue_len - 1;
}
}
//入队列
assist_queue[tail_pos] = i;
queue_len += 1;
tail_pos += 1;
//达到窗口大小,输出窗口内最大值(最左边)
if(i + 1 >= window_len){
printf("%d,", array[assist_queue[head_pos]]);
}
}
printf("]\n");
free(assist_queue);
assist_queue = NULL;
return 0;
}
int main(){
int array[10] = {19,12,12,2,13,14,123,1212,122,211};
int array_length = 10;
int window_len = 4;
get_windows(array, array_length, window_len);
return 0;
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/stella_alash/article/details/110944755