1029. Median (25)(C++)

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

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 (<=1000000) 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

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

题目大意:计算两个链表的有序合并后的链表的中位数。也是顺序表的一个经典题型了,用排序可能会超时,这里直接双指针遍历,遍历到第(m+n+1)/2个即可。

PS:貌似后来的测试样例改了,如果把两个数字串都存储了,空间上容易超出限制,所以可以只存储第一个,第二个就边遍历边比较,不用存储。

#include 
#include 
using namespace std;
int main(){
    int n,m,k,p=0,q=0,result,tempb,preb;
    std::vector a;
    scanf("%d",&n);
    a.resize(n);
    for(int i=0;i

优化一下下,每次移动指针的时候,顺带更新一下结果值,就省得最后还要进行比较

#include 
#include 
using namespace std;
int main(){
	int n, m, temp, target, p = 0, ans, cnt = 0;
	scanf("%d", &n);
	vectorseq(n);
	for(int i = 0; i < n; ++ i)
		scanf("%d", &seq[i]);
	scanf("%d", &m);
	target = ((m + n + 1) >> 1);
	for(int i = 0; cnt < target && i < m; ++ i){
		scanf("%d", &temp);
		while(cnt < target && p < n && seq[p] <= temp){
			ans = seq[p++];
			++ cnt;
		}
		if(cnt ++ < target)
			ans = temp;
	}
	while(cnt ++ < target)
	  ans = seq[p++];
	printf("%d", ans);
}

emmmmmm其实这道题说难也不难,说简单也不简单,每次刷都有新感觉hu(。-ω-)zzz这次做的时候,到了结果值,就直接return 0了。其实大同小异,关于边界的处理方式各有各好处,还需要读者自己体会。

#include 
#include 
using namespace std;
int main(){
	int n, m, cnt = 0, p = 0, temp, ans;
	scanf("%d", &n);
	vectorseq(n);
	for(int i = 0; i < n; ++ i)
		scanf("%d", &seq[i]);
	scanf("%d", &m);
	ans = (m + n + 1) / 2;
	for(int i = 0; i < m; ++ i){
		scanf("%d", &temp);
		while(cnt < ans && p < n && seq[p] <= temp){
			++ cnt;
			++ p;
		}
		if(cnt == ans){
			printf("%d", seq[p - 1]);
			return 0;
		}
		if(++ cnt == ans){
			printf("%d", temp);
			return 0;
		}
	}
	printf("%d", seq[p + ans - cnt - 1]);
}

 

你可能感兴趣的:(PAT甲级)