1029 Median(排序)

1029 Median

0、题目

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×105) 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

1、大致题意

给出两个已排序序列,求这两个序列合并后的中间数

2、基本思路

其实可以存储两个数组,然后 sort 大法。

但是我一开始想到的是 priority_queue ,那就两种都做一下吧。

3、解题过程

3.1 priority_queue 取出指定下标的数

这边有个坑,就是因为你不能直接取出指定下标的数,所以你只能遍历 s i z e 2 \frac{size}{2} 2size 次,然后取出中位数。

但是奇数和偶数的中位数的取法不一样,奇数是取到 i<=size/2 ;偶数是取到 i<size/2

3.1.1 第一份代码(18/25)

在第一份代码里面就是没有区分出来奇数和偶数,所以出错

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

priority_queue<int,vector<int>,greater<int> > q;

int main() {
	int n,m;
	while(!q.empty()) {
		q.pop();
	}
	scanf("%d",&n);
	for(int i=0; i<n; i++) {
		scanf("%d",&m);
		q.push(m);
	}
	scanf("%d",&n);
	for(int i=0; i<n; i++) {
		scanf("%d",&m);
		q.push(m);
	}
	int size=q.size();
	size=size/2;
	while(size){
		n=q.top();
		q.pop();
		size--;
	}
	n=q.top();
	cout<<n;
	return 0;
}

在这里插入图片描述

3.1.2 AC代码
#include<queue>
#include<iostream>
using namespace std;

priority_queue<int,vector<int>,greater<int> > q;

int main() {
	int n,m;
	while(!q.empty()) {
		q.pop();
	}
	scanf("%d",&n);
	for(int i=0; i<n; i++) {
		scanf("%d",&m);
		q.push(m);
	}
	scanf("%d",&n);
	for(int i=0; i<n; i++) {
		scanf("%d",&m);
		q.push(m);
	}
	int size=q.size();
	if(size%2==0) {
		for(int i=0; i<size/2; i++) {
			n=q.top();
			q.pop();
		}
	} else {
		for(int i=0; i<=size/2; i++) {
			n=q.top();
			q.pop();
		}
	}
	cout<<n;
	return 0;
}

在这里插入图片描述

3.2 第二种思路

#include <bits/stdc++.h>
using namespace std;

int a[400005];
 
int main(){
    int n,m;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
    scanf("%d",&m);
    for(int i=0;i<m;i++)
        scanf("%d",&a[n+i]);
    sort(a,a+m+n);
    int mid=(m+n-1)/2;
    cout<<a[mid]<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值