7-53-两个有序序列的中位数-编程题
程序员文章站
2022-06-07 18:54:03
...
解题代码
#include<stdio.h>
#include<stdlib.h>
int Re(int a[], int left, int right, int K);
int main()
{
int num, i, j, left, right, t;
scanf("%d", &num);
int *a = (int *)malloc(num * 2 * sizeof(int));
for (i = 0; i < num * 2; i++) {
scanf("%d", &a[i]);
}
left = 0, right = num * 2 - 1;
int re = Re(a, left, right, num + 1);
printf("%d", re);
return 0;
}
int Re(int a[], int left, int right, int K) {
int e = a[left];
int l = left, r = right;
int t;
while (l <= r) {
while (l <= r&&a[l] >= e) l++;
while (r>=l&&a[r] < e) r--;
if (l < r) {
t; t = a[l]; a[l] = a[r]; a[r] = t;
}
}
t = a[l - 1]; a[l - 1] = a[left]; a[left] = t;
if (l - left - 1 >= K) return Re(a, left, l - 2, K);
else if (l - left - 1 < K - 1) return Re(a, l, right, K - l + left);
else return e;
}
测试结果
问题整理
1.注意循环的判断条件。
上一篇: 1056 组合数的和