【PAT甲级】1029 Median

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

题目大意

这题就是给出两个有序的递增数列,要求将两个数列合并成一个非递减数列,并输出合并后的数列中位数,如果是偶数个则输出第cnt/2个。

个人思路

这题其实用了算法笔记中的two points的思路,即对两个数组从左到右对下标和下标对应的数字进行比较操作,选出较小的数加入合并数组,同时对被这个数字对应对数组下标+1,从左到右扫描一遍,如果某个源数组还有剩余数字,则将剩下的直接加入合并数组。这题应该是通过源数组的数字数量来卡时间的,如果用二层循环做肯定会超时,所以要在o(n)的时间内完成合并。另外如果使用cin和cout可能会超时,所以记得用printf和scanf。

实现代码

#include <cstdio>
#include <iostream>
#define ll long long
#define maxn 200005
using namespace std;

int main() {
    int n1, n2; // 数字个数
    int nums1[maxn], nums2[maxn], nums[maxn*2]; // 两个有序数组和合并数组
    
    // input
    cin >> n1;
    for (int i = 0; i < n1; i ++) {
        scanf("%d", &nums1[i]);
    }
    cin >> n2;
    for (int i = 0; i < n2; i ++) {
        scanf("%d", &nums2[i]);
    }
    
    // 将两个有序数组合并到至少一个数组合并完毕
    int index1 = 0, index2 = 0, cnt = 0;
    while (index1 < n1 && index2 < n2) {
        if (nums1[index1] <= nums2[index2]) {
            nums[cnt++] = nums1[index1++];
        }
        else {
            nums[cnt++] = nums2[index2++];
        }
    }
    
    // 将剩余的数组合并
    while (index1 < n1) {
        nums[cnt++] = nums1[index1++];
    }
    while (index2 < n2) {
        nums[cnt++] = nums2[index2++];
    }
    
    // output
    if (cnt % 2 == 0)
        printf("%d\n", nums[cnt/2-1]);
    else
        printf("%d\n", nums[cnt/2]);
    
    return 0;
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值