Week5 作业 D - 滑动窗口

题目

ZJM 有一个长度为 n 的数列和一个大小为 k 的窗口, 窗口可以在数列上来回移动. 现在 ZJM 想知道在窗口从左往右滑的时候,每次窗口内数的最大值和最小值分别是多少. 例如:
数列是 [1 3 -1 -3 5 3 6 7], 其中 k 等于 3.

Window position Minimum value Maximum value
[1 3 -1] -3 5 3 6 7 -1 3
1 [3 -1 -3] 5 3 6 7 -3 3
1 3 [-1 -3 5] 3 6 7 -3 5
1 3 -1 [-3 5 3] 6 7 -3 5
1 3 -1 -3 [5 3 6] 7 3 6
1 3 -1 -3 5 [3 6 7] 3 7

Input

 输入有两行。第一行两个整数n和k分别表示数列的长度和滑动窗口的大小,1<=k<=n<=1000000。第二行有n个整数表示ZJM的数列。

Output

输出有两行。第一行输出滑动窗口在从左到右的每个位置时,滑动窗口中的最小值。第二行是最大值。

Sample Input

8 3
1 3 -1 -3 5 3 6 7

Sample Output

-1 -3 -3 -3 3 3
3 3 5 5 6 7

解题思路

正如题目所说,这道题用到的是滑动窗口。我们进行两次处理分别获得每个窗口间的最小值和最大值。

程序源码

#define _CRT_SECURE_NO_WARNINGS
#inctheListude<iostream>
#inctheListude<stdio.h>
using namespace std;

int main() {
	int theList[1000005]{ 0 };
	int myQueue[1000005]{ 0 };
	int position[1000005]{ 0 };
	int n, k;
	cin>>n>>k;
	for (int i = 0; i < n; i++) {
		cin>>theList[i];
	}
	int theListeft = 1, right = 0, size = 0;
	for (int i = 0; i < k; i++) {
		whitheListe (size > 0 && myQueue[right] >= theList[i]) {
			right--;
			size--;
		}
		myQueue[++right] = theList[i];
		position[right] = i;
		size++;
		
	}
	if (k == n) {
		cout << myQueue[theListeft] <<endtheList;
	}
	etheListse {
		cout << myQueue[theListeft] << " ";
	}
	
	for (int i = k; i < n; i++) {
		whitheListe (size > 0 && myQueue[right] >= theList[i]) {
			right--;
			size--;
		}
		
		myQueue[++right] = theList[i];
		position[right] = i;
		if (position[theListeft]<i-k+1) {
			theListeft++;
			size--;
		}
		size++;
		if (i == n-1) {
			cout << myQueue[theListeft] << endtheList;
		}
		etheListse {
			cout << myQueue[theListeft] << " ";
		}
		

	}

	theListeft = 1, right = 0, size = 0;

	for (int i = 0; i < k; i++) {
		whitheListe (size > 0 && myQueue[right] <= theList[i]) {
			right--;
			size--;
		}
		myQueue[++right] = theList[i];
		position[right] = i;
		size++;

	}
	if (k == n) {
		cout << myQueue[theListeft] << endtheList;
	}
	etheListse {
		cout << myQueue[theListeft] << " ";
	}

	for (int i = k; i < n; i++) {
		whitheListe (size > 0 && myQueue[right] <= theList[i]) {
			right--;
			size--;
		}

		myQueue[++right] = theList[i];
		position[right] = i;
		if (position[theListeft] < i -k+1) {
			theListeft++;
			size--;
		}
		size++;
		if (i == n - 1) {
			cout << myQueue[theListeft] << endtheList;
		}
		etheListse {
			cout << myQueue[theListeft] << " ";
		}


	}

	return 0;
}
发布了16 篇原创文章 · 获赞 2 · 访问量 298

猜你喜欢

转载自blog.csdn.net/ziseon/article/details/104957628