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 nondecreasing 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.
给定N个整数的递增序列S,中值是位于中间位置的数字。例如,S1={11,12,13,14}的中值是12,S2={9,10,15,16,17}的中值为15。两个序列的中值被定义为包含两个序列所有元素的非递减序列的中值。例如,S1和S2的中值为13。
给定两个递增的整数序列,要求您找到它们的中值。
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (≤2×105) 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.
每个输入文件包含一个测试用例。每个案例占用2行,每行给出一个序列的信息。对于每个序列,第一个正整数N(≤2×105)是该序列的大小。然后后面跟着N个整数,用空格分隔。保证所有的整数都在长int的范围内。
Output Specification:
For each test case you should output the median of the two given sequences in a line.
对于每个测试用例,您应该在一行中输出两个给定序列的中值。
Sample Input:
4 11 12 13 14
5 9 10 15 16 17
Sample Output:
13
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(bf);
in.nextToken();
int n = (int) in.nval;
int[] arr1 = new int[n];
for (int i = 0; i < n; i++) {
in.nextToken();
arr1[i] = (int) in.nval;
}
in.nextToken();
int m = (int) in.nval;
int[] arr2 = new int[m];
for (int i = 0; i < m; i++) {
in.nextToken();
arr2[i] = (int) in.nval;
}
System.out.println(findMedianSortedArrays(arr1, arr2));
}
public static int findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums;
int m = nums1.length;
int n = nums2.length;
nums = new int[m + n];
if (m == 0) {
if (n % 2 == 0) {
return nums2[n / 2 - 1] ;
} else {
return nums2[n / 2];
}
}
if (n == 0) {
if (m % 2 == 0) {
return nums1[m / 2 - 1] ;
} else {
return nums1[m / 2];
}
}
int count = 0;
int i = 0, j = 0;
while (count != (m + n)) {
if (i == m) {
while (j != n) {
nums[count++] = nums2[j++];
}
break;
}
if (j == n) {
while (i != m) {
nums[count++] = nums1[i++];
}
break;
}
if (nums1[i] < nums2[j]) {
nums[count++] = nums1[i++];
} else {
nums[count++] = nums2[j++];
}
}
if (count % 2 == 0) {
return nums[count / 2 - 1] ;
} else {
return nums[count / 2];
}
}
}