Problem
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
Understanding
Median, 在統(tǒng)計(jì)學(xué)中叫做中位數(shù),能夠?qū)⒁粋€(gè)數(shù)列分成不包含其自身的兩個(gè)部分,兩個(gè)部分長(zhǎng)度相等。如果是處理一個(gè)有序數(shù)組,則如果數(shù)組長(zhǎng)度為奇數(shù),則取中間位,如果為偶數(shù)則取中間兩數(shù)的均值。
測(cè)試用例
[1,3]
[2,3]
2.5
[1,10]
[2,3]
2.5
解法
歸并排序通過(guò)合并兩個(gè)有序的數(shù)列得到一個(gè)新有序數(shù)列,這就是解法的思想。然后取中間的一位或者兩位的均值。
不過(guò),與歸并排序的不同的是,并不需要實(shí)際的合并,只需要找到最后數(shù)組的中間一位或者兩位數(shù)即可。使用兩個(gè)變量last,cur來(lái)記錄即可。
空間復(fù)雜度O(1), 時(shí)間復(fù)雜度O(m+n)
代碼(C++)
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
const int length=nums1.size()+nums2.size();
const int indexEnd=(length%2==0)?(length+1)/2:length/2;
int i1=0,i2=0;
int index=0;
int cur,last;
while(i1 < nums1.size() && i2<nums2.size() && index <=indexEnd )
{
index++;
last=cur;
if(nums1[i1]>nums2[i2])
cur=nums2[i2++];
else
cur=nums1[i1++];
}
while(i1 < nums1.size() && index <=indexEnd)
{
last=cur;
cur=nums1[i1++];
index++;
}
while(i2 < nums2.size() && index <= indexEnd)
{
last=cur;
cur=nums2[i2++];
index++;
}
return length%2==0?(last+cur)/2.0:cur;
}
};