欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PAT 甲级 A1029 Median

程序员文章站 2022-07-15 13:26:25
...

自己写的代码

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1000010;
const int INF = 0x3fffffff;
int n1[maxn], m1[maxn];

int main() {
	int n, m;
	scanf("%d", &n);
	for(int i = 0; i < n; i++) {
		scanf("%d", &n1[i]);
	}
	scanf("%d", &m);
	for(int i = 0; i < m; i++) {
		scanf("%d", &m1[i]);
	}
	n1[n] = m1[m] = INF;
	int medianpos = (m + n - 1) / 2; // 数组下标从0开始
	int i = 0, j = 0, count = 0;
	while(count < medianpos) {
		if(n1[i] < m1[j]) i++;
		else j++;
		count++;
	} 
	if(n1[i] < m1[j]) printf("%d\n", n1[i]);
	else printf("%d\n", m1[j]);
	return 0;
}






算法笔记中的代码 使用two pointer

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1000010;
const int INF = 0x3fffffff;
int n1[maxn], m1[maxn];

int main() {
	int n, m;
	scanf("%d", &n);
	for(int i = 0; i < n; i++) {
		scanf("%d", &n1[i]);
	}
	scanf("%d", &m);
	for(int i = 0; i < m; i++) {
		scanf("%d", &m1[i]);
	}
	n1[n] = m1[m] = INF;
	int medianpos = (m + n - 1) / 2; // 数组下标从0开始
	int i = 0, j = 0, count = 0;
	while(count < medianpos) {
		if(n1[i] < m1[j]) i++;
		else j++;
		count++;
	} 
	if(n1[i] < m1[j]) printf("%d\n", n1[i]);
	else printf("%d\n", m1[j]);
	return 0;
}






 

相关标签: PAT甲级 PAT甲级