【PAT】1029. Median (25)

题目


链接:https://www.patest.cn/contests/pat-a-practise/1029

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.

Input

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 (<=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.

Output

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




分析


题意:

求中位数
求中位数。

把两个序列合并后,求中间即可

9 10 11 12 13 14 15 16 17

9个数,中间数 (9 - 1) / 2 == 4; [下标0开始]




题解(已AC)


/**
    2018.2.3
    Donald
*/
//1029. Median (25)

/**
    求中位数。

    把两个序列合并后,求中间即可

    9 10 11 12 13 14 15 16 17

    9个数,中间数 (9 - 1) / 2 == 4; [下标0开始]
*/


#include<cstdio>
#include<vector>
using namespace std;
#define MAXN 1000005

int N1, N2;
long seq1[MAXN];
long seq2[MAXN];
vector<long> Vec;

int main(void) {

    scanf("%d", &N1);
    for (int i = 0; i < N1; ++i) {
        scanf("%ld", &seq1[i]);
    }

    scanf("%d", &N2);
    for (int i = 0; i < N2; ++i) {
        scanf("%ld", &seq2[i]);
    }

    int i = 0, j = 0, k = 0;
    while ( i < N1 && j < N2) {
        if (seq1[i]  == seq2[j]) {
            Vec.push_back(seq1[i++]);
            Vec.push_back(seq2[j++]);
        } else if (seq1[i] < seq2[j]) {
            Vec.push_back(seq1[i++]);
        } else {
            Vec.push_back(seq2[j++]);
        }
    }

    while (i < N1) {
        Vec.push_back(seq1[i++]);
    }

    while (j < N2) {
        Vec.push_back(seq2[j++]);
    }

    printf("%ld", Vec[(Vec.size() - 1) / 2]);

    return 0;
}


猜你喜欢

转载自blog.csdn.net/fanfan4569/article/details/79258849