PAT (Advanced Level) Practice:1029 Median (25分)

1029 Median (25分)

中位数

归并排序的思想,使用两个指针,指向两个数组的头部,比较大小,小的数字更新到res中。循环(n1+n2)/2次。
根据柳神代码的改进:
如果一个数字走到头了也找不到中位数,那么直接使用数学公式得到结果,跳出循环。
例如:
1 1
4 1 2 3 4

代码

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

int main()
{
	int n1, n2;
	cin >> n1;
	vector<int> s1(n1, 0);
	for (int i = 0; i < n1; i++)
	{
		cin >> s1[i];
	}
	cin >> n2;
	vector<int> s2(n2, 0);
	for (int i = 0; i < n2; i++)
	{
		cin >> s2[i];
	}
	int i = 0, j = 0;
	int stop = n1 + n2;
	if (stop % 2 == 0)
	{
		stop /= 2;
	}
	else
	{
		stop++;
		stop /= 2;
	}
	int res;
	while (i + j < stop)
	{
		if (i<n1&&j<n2&&s1[i] < s2[j])
		{
			res = s1[i];
			i++;
		}
		else if(i<n1&&j<n2&&s1[i]>s2[j])
		{
			res = s2[j];
			j++;
		}
		else if(i>=n1)
		{
			res = s2[stop-n1-1];
                        break;
		}
		else
		{
			res = s1[stop-n2-1];
                        break;
		}
	}
	cout << res << endl;
	return 0;
}
posted @ 2021-01-24 21:45  韩天尊  阅读(29)  评论(0)    收藏  举报