1. 程式人生 > 其它 >2020-12-10

2020-12-10

技術標籤:程式設計演算法資料結構C

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;
}