PAT甲级真题 1029 Median (25分) C++实现(归并排序思想,两个有序数组找中位数)

本文介绍了一种算法,用于找到两个给定的有序整数数组的中位数。通过使用类似归并排序的双指针技术,该算法有效地确定了合并序列中位于中间位置的元素。

摘要生成于 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 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×10^​5​​ ) 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 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

思路

两个数组中位数的位置mid = (n1 + n2 - 1) / 2(从0计数)。

按照归并排序的思想,用两个指针分别指向两个有序数组的开始位置,移动较小一方的指针,直到移动次数达到mid为止。

需要注意的是,数据量大,程序开头添加:

    ios::sync_with_stdio(false);
    cin.tie(0);

以提高cin效率,否则最后一个测试点超时。

代码

#include <iostream>
#include <vector>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    vector<vector<int> > a(2);
    for (int i=0; i<2; i++){
        int n;
        cin >> n;
        a[i].resize(n);
        for (int j=0; j<n; j++){
            cin >> a[i][j];
        }
    }
    int i = 0;
    int j = 0;
    int mid = (a[0].size() + a[1].size() - 1) / 2;
    int count = -1;
    while (i<a[0].size() && j<a[1].size()){
        count++;
        if (a[0][i] < a[1][j]){
            if (count==mid){
                cout << a[0][i];
                break;
            }
            i++;
        }
        else{
            if (count==mid){
                cout << a[1][j];
                break;
            }
            j++;
        }
    }

    if (count < mid){
        count++;
        if (i==a[0].size()){
            while(count<mid){
                count++;
                j++;
            }
            cout << a[1][j];
        }
        else if(j==a[1].size()){
            while(count<mid){
                count++;
                i++;
            }
            cout << a[0][i];
        }
    }
    cout << endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值