题目1004:Median

来源:互联网 发布:剑灵召唤师捏脸数据图 编辑:程序博客网 时间:2024/05/16 03:00
题目1004:Median

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:13557

解决:3744

题目描述:

    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 145 9 10 15 16 17
样例输出:
13 
代码如下:(这是第一版答案,很粗糙,也不需要解释)
import java.util.Arrays;import java.util.Scanner;public class Media {public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNext()){int count1 = sc.nextInt();long[] a = new long[count1];for(int i=0;i<count1;i++){a[i] = sc.nextLong();}int count2 = sc.nextInt();long[] b = new long[count2];for(int i=0;i<count2;i++){b[i] = sc.nextLong();}long[] c = Arrays.copyOf(a, count1+count2);System.arraycopy(b, 0, c, count1, count2);Arrays.sort(c);if((count1+count2)%2==0) System.out.println(c[(count1+count2)/2-1]);else System.out.println(c[(count1+count2)/2]);}}}
第二版改进后如下,不需要拷贝数组了
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Scanner;import java.util.stream.Collectors;public class Media_java8 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);ArrayList<Integer> num = new ArrayList<Integer>();while(sc.hasNext()){int count1 = sc.nextInt();for(int i=0;i<count1;i++){num.add(sc.nextInt());}int count2 = sc.nextInt();for(int i=0;i<count2;i++){num.add(sc.nextInt());}//进行数字排序,收集成列表,提取中位数System.out.println(num.stream().sorted().collect(Collectors.toList()).get((count1+count2)/2-1+(count1+count2)%2));}}}
0 0
原创粉丝点击