7-3 兩個有序序列的中位數 (25分)
已知有兩個等長的非降序序列S1, S2, 設計函數求S1與S2並集的中位數。有序序列,的中位數指A(N−1)/2的值,即第⌊個數(A0為第1個數)。 輸入格式: 輸入分三行。第一行給出序列的公共長度N(0<N≤100000),隨后每行輸入一個序列的信息,即N個非降序排列的整數。數字用空格間隔。 輸出格式: 在一行中輸出兩個輸入序列的並集序列的中位數。 輸入樣例1: 5 1 3 5 7 9 2 3 4 5 6 輸出樣例1: 4 輸入樣例2: 6 -100 -10 1 1 1 1 -50 0 2 3 4 5 輸出樣例2: 1
代碼如下:
一、n不大時,實現功能的相對簡潔形式
#include <stdio.h> #include <stdlib.h> int main(int argc, const char *argv[]) { int n, i, j, temp=0; int *s = (int*)malloc(10000*sizeof(int)); scanf("%d",&n); for(i=0; i<2*n; i++) { scanf("%d",&s[i]); } for(i=0; i<2*n; i++) { for(j=i+1; j<2*n; j++) { if(s[i] < s[j]) { temp = s[i]; s[i] = s[j]; s[j] = temp; } } } printf("%d", s[(2*n-1)/2]); free(s); return 0; }
二、n取最大時,可以通過PAT編譯的代碼
#include <stdio.h> #include <stdlib.h> int merge(int *a, int m, int *b, int n, int *c); void Input(int *Array, int n); int main(int argc, const char *argv[]) { int n, i, index; int a[100000],b[100000],c[200000]; //調用動態內存在PAT會出錯 scanf("%d",&n); Input(a,n); Input(b,n); index = merge(a,n,b,n,c)-1; //數組長度-1 = 數組最大下標 printf("%d", c[(index-1)/2]); //按照定義輸出中位數 return 0; } int merge(int *a, int m, int *b, int n, int *c) //順序數組,合並至2n { //參數m和n分別是數組a和數組b的長度 int i=0, j=0, k=0; while(i<m && j<n) { if (a[i] < b[j]) c[k++] = a[i++]; else if(b[j] < a[i]) c[k++] = b[j++]; else { c[k++] = a[i++]; c[k++] = b[j++]; } } while(i < m) //復制剩余數據段 c[k++] = a[i++]; while(j < n) //復制剩余數據段 c[k++] = b[j++]; return k; //返回數值k是數組c的長度 } void Input(int *Array, int n) //輸入順序數組 { int i; for(i=0; i<n; i++) scanf("%d",&Array[i]); }