您的位置:首页 > 其它

Median of Two Sorted Arrays

2015-07-01 22:09 120 查看
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

问题描述:给定两个有序数组,从这两个有序数组中找到中值。进行详细描述,我们使用归并排序,将两个有序数组进行合并得到ret,然后只针对数组ret进行操作,得到数组元素个数len,如果len是奇数,则直接返回数组中的第len/2个,如果len是偶数,则返回len/2和len/2-1个元素的平均值,很明显的,使用归并排序即可,做这个题,俺是没看明白题目。。。一边做,看输出结果一边思考。。。

class Solution {
public:
	
	double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
		int i = 0, j =0;
		int k = i;
		vector<int> ret;		
		while (i < nums1.size() && j < nums2.size())
		{
			if (nums1.at(i) < nums2.at(j))
			{
				ret.push_back(nums1.at(i++));
			}
			else
			{
				ret.push_back(nums2.at(j++));
			}
		}
		while (i < nums1.size())
		{
			ret.push_back(nums1.at(i++));
		}
		while (j < nums2.size())
		{
			ret.push_back(nums2.at(j++));
		}
		i = ret.size();
		
		if (i % 2 == 0)
		{	
			return (ret.at(i / 2) + ret.at(i / 2 - 1))*1.0 / 2;
		}
		else
		{
			return ret.at(i/2);
		}
		
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: