7-1 两个有序序列的中位数 (25 分)

采用的是折半查找的思想 O(n)的思想很容易想到

7-1 两个有序序列的中位数 (25 分)

已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A​0​​,A​1​​,⋯,A​N−1​​的中位数指A​(N−1)/2​​的值,即第⌊(N+1)/2⌋个数(A​0​​为第1个数)。

输入格式:

输入分三行。第一行给出序列的公共长度N(0<N≤100000),随后每行输入一个序列的信息,即N个非降序排列的整数。数字用空格间隔。

输出格式:

在一行中输出两个输入序列的并集序列的中位数。

输入样例1:

5
1 3 5 7 9
2 3 4 5 6

输出样例1:

4

输入样例2:

6
-100 -10 1 1 1 1
-50 0 2 3 4 5

输出样例2:

1
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <stdio.h>
int main(){
    int str[100001],arr[100001];
    int n;scanf("%d",&n);
    for(int i=0;i<n;i++) scanf("%d",&str[i]);
    for(int i=0;i<n;i++) scanf("%d",&arr[i]);
    //中位数在大的左边 小的右边
    int start1=0,end1=n-1,mid1=(n-1)/2;
    int start2=0,end2=n-1,mid2=(n-1)/2;
    int mid;int flag=0;
    while(start1!=end1&&start2!=end2){
        if(str[mid1]==arr[mid2]) {
                mid=str[mid1];
                flag=1;
                break;
        }
        else if(str[mid1]>arr[mid2]){
            if((end1-start1)%2==0&&(end2-start2)%2==0){
                end1=mid1;
                start2=mid2;
            }
            else{
                end1=mid1;
                start2=mid2+1;
            }
            mid1=(start1+end1)/2;
            mid2=(start2+end2)/2;
        }
        else{
            if((end1-start1)%2==0&&(end2-start2)%2==0){
                start1=mid1;
                end2=mid2;
            }
            else {
                start1=mid1+1;
                end2=mid2;
            }
            mid1=(start1+end1)/2;
            mid2=(start2+end2)/2;
        }
        //printf("start2 : %d, end2 : %d, mid2 : %d\n",start2,end2,arr[mid2]);
    }
    //printf("start2 : %d\n",start2);
    if(!flag) {
        if(start1==end1) {
            int a=str[start1],b=arr[end2];
            if(a>b) mid=b;
            else mid=a;
        }
        else {
            int a=arr[start2],b=str[end1];
            if(a>b) mid=b;
            else mid=a;
        }
    }
    printf("%d\n",mid);
}

 


版权声明:本文为wuqi5328原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。