您的位置:首页 > 其它

九度——题目1004:Median

2013-03-05 18:28 309 查看
题目描述:

Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1={11, 12, 13, 14} is 12, and the median of S2={9, 10, 15, 16, 17} is 15. The median of two sequences is defined to be the median
of the non-decreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.

Given two increasing sequences of integers, you are asked to find their median.

输入:

Each input file may contain more than one test case.

Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (≤1000000) is the size of that sequence. Then N integers follow, separated by a space.

It is guaranteed that all the integers are in the range of long int.

输出:

For each test case you should output the median of the two given sequences in a line.

样例输入:
4 11 12 13 14
5 9 10 15 16 17


样例输出:
13


import java.io.BufferedInputStream;
import java.util.Scanner;

public class Main
{
/**
* @param args
*/
public static void main(String[] args)
{
Scanner cin = new Scanner(new BufferedInputStream(System.in));
int num1[], num2[], mid, count, median = 0, i, j, n, count1, count2;
while (cin.hasNext())
{
count1 = cin.nextInt();
num1 = new int[count1];
for (int k = 0; k < count1; k++)
{
num1[k] = cin.nextInt();
}
count2 = cin.nextInt();
num2 = new int[count2];
for (int k = 0; k < count2; k++)
{
num2[k] = cin.nextInt();
}
// 开始计算
count = count1 + count2;
if ((count % 2) != 0)
{
mid = (count / 2) + 1;
}
else
{
mid = (count / 2);
}
for (i = 0, j = 0, n = 1; (i < num1.length) && (j < num2.length)
&& (n <= mid); n++)
{
if (num1[i] < num2[j])
{
if (n == mid)
{
median = num1[i];
}
i++;
}
else
{
if (n == mid)
{
median = num2[j];
}
j++;
}
}
if (n <= mid)
{
for (; i < num1.length; i++, n++)
{
if (n == mid)
{
median = num1[i];
}
}
for (; j < num2.length; j++, n++)
{
if (n == mid)
{
median = num2[j];
}
}
}
System.out.println(median);
}
}
}

/**************************************************************
Problem: 1004
User: 忆、瞻
Language: Java
Result: Accepted
Time:200 ms
Memory:18528 kb
****************************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: