进阶实验1-3.1-两个有序序列的中位数-编程题
程序员文章站
2022-03-13 15:58:06
...
解题代码
#include<stdio.h>
#include<stdlib.h>
int Re(int a[], int left, int right, int K);
int main()
{
int N;
scanf("%d", &N);
int *a = (int *)malloc((2 * N + 1) * sizeof(int));
int i;
for (i = 0; i < 2 * N; i++) {
scanf("%d", &a[i]);
}
int median = Re(a, 0, 2 * N - 1, N + 1);
printf("%d", median);
return 0;
}
int Re(int a[], int left, int right, int K) {
//int j;
//for (j = left; j <= right; j++) {
// printf("%d ", a[j]);
//}
//printf("\n");
int l = left, r = right;
int e = a[l];
int t;
while (left <= right) {
if (left == right&&a[left] < e) break;
while (left <= right&&a[left] >= e) left++;
while (right > left&&a[right] < e) right--;
if (left < right) {
t = a[left];
a[left] = a[right];
a[right] = t;
}
}
t = a[left - 1];
a[left - 1] = a[l];
a[l] = t;
//printf("left=%d,right=%d,l=%d,K=%d\n\n", left, right, l, K);
if ((left - 2 - l + 1) > K - 1) {
return Re(a, l, left - 2, K);
}
else if ((left - 2 - l + 1) < K - 1)
{
return Re(a, left, r, K - (left - 1 - l) - 1);
}
else return a[left - 1];
}
测试结果
问题整理
1.干他妈的这题。
2.学会e方法排序分解数列递归求中位数。
3.注意N最小的情况。