携程旅行网 2018校招 研发类在线考试
编程题|20.0分2/3
合并数组的的中位数
时间限制:C/C++语言 1000MS;其他语言 3000MS
内存限制:C/C++语言 65536KB;其他语言 589824KB
题目描述:
两个已排好序的数组,找出两者合并后的数组的中位数。
例如:
给出A=[1,2,3,4,5,6]和B=[2,3,4,5],它们合并后的数组是[1,2,3,4,5,6],合并后数组的中位数是3.5(注:(3+4)/2)。
给出A=[1,2,3]和B=[4,5],它们合并后的数组是[1,2,3,4,5],合并后数组的中位数是3。
输入
第一行读入一个正整数n,表示第一个数组的元素个数,第二行读入n个递增整数,表示第一个排好序的数组,第三行读入一个正整数m,表示第二个数组的元素个数,第四行读入m个递增整数,表示第二个排好序的数组
样例输入
6
1 2 3 4 5 6
4
2 3 4 5
样例输出
3.5
——————————————————————————————————
以上是题目,下面是我的代码,不知道为什么通过率只有11%,求大神解答,多谢了
using System;
using System.Linq;
namespace Ctrip
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
var first = changeInt(Console.ReadLine().Split(' '));
int m = int.Parse(Console.ReadLine());
var second = changeInt(Console.ReadLine().Split(' '));
int i = 0;
int j = 0;
var result = new int[m + n];
int index = 0;
while (i < n && j < m)
{
if (first[i] < second[j])
{
result[index] = first[i];
i++;
}
else if (first[i] == second[j])
{
result[index] = first[i];
i++;
j++;
}
else
{
result[index] = second[j];
j++;
}
index++;
}
if (i < n)
{
for (; i < n; i++)
{
result[index] = first[i];
index++;
}
}
if (j < m)
{
for (; j < m; j++)
{
result[index] = second[j];
index++;
}
}
if (index % 2 == 0)
{
var middle = index / 2;
var r = float.Parse((result[middle - 1] + result[middle]).ToString());
r = r / 2;
Console.WriteLine(r);
}
else
{
int middle = index / 2;
Console.WriteLine(result[middle]);
}
}
static int[] changeInt(string[] input)
{
var arr = new int[input.Length];
for (int i = 0; i < input.Length; i++)
{
arr[i] = int.Parse(input[i]);
}
return arr;
}
}
}