PAT甲级1029 Median (25分)|C++实现

博客介绍了PAT甲级编程题1029 Median的解题方法,包括题目描述、输入输出规格、示例输入输出。作者使用双指针法,无需完全排序两个递增序列,直接找到它们的中位数。AC代码简洁易懂。
摘要由CSDN通过智能技术生成

一、题目描述

原题链接
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:

在这里插入图片描述

​​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

二、解题思路

这道题主要是将两个数组中的数进行排序,随后把在中间的数输出即可。这里用的是双指针法,不难理解,代码也非常简单,这里为了省时间,我并没有把两个数组完整排列出来,而是采用了到了位置就输出的方法。代码非常易理解,附在下方。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
const int maxn = 200010;
typedef long long LL;
LL a[maxn] = {0}, b[maxn] = {0};
int main()
{
  int na, nb, cnt=0;
  scanf("%d", &na);
  for(int i=1; i<=na; i++)
    scanf("%lld", &a[i]);
  scanf("%d", &nb);
  for(int i=1; i<=nb; i++)
    scanf("%lld", &b[i]);
  int ptr_a = 1, ptr_b = 1;
  int mk;
  if((na+nb)%2 == 0)	mk = (na+nb)/2;
  else	mk = (na+nb)/2 + 1;
  while(ptr_a<=na && ptr_b<=nb)
  {
    cnt++;
    if(a[ptr_a] < b[ptr_b])
    {
      ptr_a++;
      if(cnt == mk)
      {
        printf("%lld", a[ptr_a-1]);
        return 0;
      }
    }
      
    else
    {
      ptr_b++;
      if(cnt == mk)
      {
        printf("%lld", b[ptr_b-1]);
        return 0;
      }
    }
  }
  if(cnt < mk)
    printf("%lld", ptr_a == na+1 ? b[ptr_b+mk-cnt-1] : a[ptr_a+mk-cnt-1]);
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值