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