题解 | #取中值#
取中值
https://www.nowcoder.com/practice/d69e75bb224e4a7785a02b2acc0821c4
这题的中位数不需要排序,合并完输出数组的最中间那个数就行。
#include <iostream> using namespace std; #define N 1000000 void input(int a[],int n){ for (int i = 0; i < n; i++) cin >>a[i]; } int merge(int x[],int y[],int z[],int a,int b,int c,int d){ int j = 0; for (int i = a-1;i<b;i++){ z[j++] = x[i]; } for (int i = c-1;i<d;i++){ z[j++] = y[i]; } // for (int i = 0;i<j;i++){ // cout <<z[i]<<endl; // } return j; } void Mysort(int a[],int n){ for (int i = 0; i<n;i++){ for (int j = 0; j < n-i-1;j++){ if (a[j] > a[j+1]){ int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } int main(){ int n,m; while(cin >>n>>m){ int x[N],y[N],z[N]; //输入 input(x,n); input(y,m); int a,b,c,d; cin>>a>>b>>c>>d; int k = merge(x,y,z,a,b,c,d);//合并 //Mysort(z,k);//排序 // for(int i = 0; i < k;i++){ // cout <<z[i]<<" "; // } //中位数 if (k%2!=0) cout <<z[k/2]; else cout <<z[k/2-1]; } }