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)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
int main()
{
vector<int>nums1;
vector<int>nums2;
int m, n;
while (cin >> m >> n)
{
for (int i = 0; i < m; i++)
{
int x;
cin >> x;
nums1.push_back(x);
}
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
nums2.push_back(x);
}
int flag = (m + n) % 2 == 0? 1 : 0; //个数为偶数,则flag = 1
int mpos = (m + n) / 2;
if (flag)mpos -= 1; //如果为偶数的话,则找两个数中第一个出现时的位置
int count = 0;
int tmp;
size_t i, j;
i = j = 0;
while (i < nums1.size() && j < nums2.size())
{
if (count == mpos+1)break; // mpos+1是因为count计数要与容器的位置想匹配,因为容器是从0开始的,这样的话,如果是奇数,则count = mpos+1 是,刚好对于容器中的那个元素的位置
if (nums1[i] <= nums2[j])
{
tmp = nums1[i]; //赋值要在i++前,因为如果i++后再访问容器的话,可能超出容器的范围
i++;
count++;
}
else
{
tmp = nums2[j];
j++;
count++;
}
}
if (count == mpos+1) //以及到达目的位置
{
if (flag) //如果是偶数的话
{
if (i == nums1.size())cout << (tmp + nums2[j])*1.0 / 2 << endl; //此种情况1是,虽然到达了位置,此位置刚好是1容器结束,则第二个数为2容器的元素
else if (j == nums2.size())cout << (tmp + nums1[i])*1.0 / 2 << endl;//此种情况2是,虽然到达了位置,此位置刚好是2容器结束,则第二个数为1容器的元素
else // 此种情况是,都没有到达两个容器结束
{
if (nums1[i] <= nums2[j]) //如果不做上面情况1/2处理,当遇到时,在此处理会导致访问超出容器的范围
cout << (tmp + nums1[i])*1.0 / 2 << endl;
else
cout << (tmp + nums2[j])*1.0 / 2 << endl;
}
}
else
cout << tmp*1.0 << endl;
}
else //还没有到达目标位置,但是容器1/2中某一个已结束
{
if (i == nums1.size()) //容器1结束
{
tmp = nums2[j + (mpos + 1 - count) - 1];
if (flag)
cout << (tmp + nums2[j + (mpos + 1 - count)])*1.0 / 2 << endl;
else
cout << tmp*1.0 << endl;
}
else //容器2结束
{
tmp = nums1[i + (mpos + 1 - count) - 1];
if (flag)
cout << (tmp + nums1[i + (mpos + 1 - count)])*1.0 / 2 << endl;
else
cout << tmp*1.0 << endl;
}
}
}
}
分析:
此题还是相对简单,但是考虑的情况比较多,题目中要求的时间复杂度为O(log (m+n)),表明,只有一个循环,且只遍历了(m+n)的一半,故可以想到,不可能是先排好序,所以只能先计算目标位置,然后当遍历到这个位置时,就可以求出值了;