1029. Median (25)

本文介绍了一种高效算法,用于求解两个已排序整数数组的中位数。通过合并两个数组并找到合并后数组的中间元素实现,强调了使用标准输入输出库以避免超时的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
注意点:因为给出的数据很有特点(已经有序),用快速排序的话时间复杂度为O(NlogN)还是有两个测试点通不过,通过可并排序的方法的时间复杂度为O(N+M)可以AC,注意不要用C++的流来完成数据的输入,会有很多测试点超时,要用stdio.h库的scanf()和printf()来完成
参考代码:
 
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
    int M,N;
    scanf("%d",&M);
    int *arr1 = new int[M];
    for(int i=0;i<M;i++){
        scanf("%d",arr1+i);
    }
    scanf("%d",&N);
    int *arr2 = new int[N];
    for(int i=0;i<N;i++){
        scanf("%d",arr2+i);
    }
    int K = M+N;
    int *arr3 = new int[K];
    int start = 0,p1=0,p2=0;
    while(p1!=M || p2!=N){
        if(p1==M){
            arr3[start++] = arr2[p2++];
            continue;
        }
        if(p2==N){
            arr3[start++] = arr1[p1++];
            continue;
        }
        if(arr1[p1]<arr2[p2]){
            arr3[start++] = arr1[p1++];
        }else{
            arr3[start++] = arr2[p2++];
        }
    }
    if(K%2==0)
        printf("%d",arr3[K/2-1]);
    else
        printf("%d",arr3[K/2]);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值