1029 Median (25分) 使用nth_element函数与两点法

121 篇文章 0 订阅
115 篇文章 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×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

 

题解: (多种解法STL/两点法/)

题目很简单,给两个数组,输出共同的中位数。坑在时间限制。

注意点:数组要开的比较大 4*10^5  所以需要在全局变量里设置。

时间限制非常严格,只能用scanf 输入,不要用 cin cout

方法一:(直接用STL)

一开始想直接用stl 里的 nth_element()函数,直接排除中间的数。

nth_element用法: 假设数组a[]的第0~n个位置有数,可以求出任意第k个位置的数。k前的小于k,k后的大于k

   nth_element(a, a + madin, a + n1 + n2); 中间的参数是需要找的。

原理:

这个函数的期望复杂度是O(n)的
在当前区间[L,R]上,找一个基准位置mid
通过线性的扫描交换,
使得[L,mid)的元素都比mid小,(mid,R]的元素都比mid大
此时mid上的元素就是第mid小的
然后判断k在哪半边,继续递归处理

图示:

代码非常简单:

#include <iostream>
#include <algorithm>

using namespace std;

int n1, a[400010], n2, median;
int main() {
	scanf("%d", &n1);
	for (int i = 0; i < n1; i++)//0~n1-1
		scanf("%d", &a[i]);
	scanf("%d", &n2);
	for (int i = 0; i < n2; i++)//n1~n2-1
		scanf("%d", &a[i + n1]);

	median = (n1 + n2 - 1) / 2;
	nth_element(a, a + median, a + n1 + n2);
	printf("%d", a[median]);
    return 0;
}

方法二:(two pointers)

解释:两点法的思想用在本题上非常巧妙,因为题干是两个递增序列

比如题干上的两个数组: S1 = { 11, 12, 13, 14 } 用i从第一个开始遍历

                                        S2 = { 9, 10, 15, 16, 17 } 用j从第一个开始遍历

不断比较两个数组当前值的大小,保留两个数中最小的,排出第0~median个数(需要设置最大值INF)

#include <iostream>
#include <algorithm>

using namespace std;

const int INF = 0x7fffffff;
int n1, n2, median;
int s1[200010], s2[200010];
int main() {
	scanf("%d", &n1);
	for (int i = 0; i < n1; i++)//0~n1-1
		scanf("%d", &s1[i]);
	scanf("%d", &n2);
	for (int i = 0; i < n2; i++)//n1~n2-1
		scanf("%d", &s2[i]);
    s1[n1] = s2[n2] = INF;
	median = (n1 + n2 - 1) / 2;
	int i = 0, j = 0, count = 0;
	while (count < median)
	{
		if (s1[i] < s2[j]) i++;
		else j++;
		count++;
	}
	if (s1[i] < s2[j])
		printf("%d", s1[i]);
	else 
		printf("%d", s2[j]);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值