问题链接:https://leetcode.com/problems/median-of-two-sorted-arrays/
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)).
c++ 40ms
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int mid = (nums1.size() + nums2.size() - 1)/2;
int flag = (nums1.size() + nums2.size())%2;
int index1 = 0, index2 = 0, temp = 0;
double medina = 0;
while ((index1 < nums1.size() || index2 < nums2.size()) && (index1 + index2) <= mid + 1)
{
if (index1 == nums1.size())
{
temp = nums2[index2];
++index2;
}
else if (index2 == nums2.size())
{
temp = nums1[index1];
++index1;
}
else if (nums1[index1] < nums2[index2])
{
temp = nums1[index1];
++index1;
}
else
{
temp = nums2[index2];
++index2;
}
if ((index1 + index2 - 1) == mid)
{
medina += temp;
}
if (!flag&&(index1 + index2 - 1) == mid + 1)
{
medina += temp;
}
}
if (!flag)
medina /= 2;
return medina;
}
};
原文:http://my.oschina.net/u/2313065/blog/523448