题目
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)).
You may assume nums1 and nums2 cannot be both empty.
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
解法:
先算好要读入的个数和位置,再按nums1和nums2 逐个读入,直到要取值的位置,读入数值,最后返回
代码如下:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int totalLen = nums1.size() + nums2.size();
int selIdx = ceil(totalLen*0.5);
int selNum = totalLen % 2 == 1 ? 1 : 2;
int calNum = selNum;
int read2Num = 0;
int read1Num = 0;
double cacheNum = 0;
for (int i = 0; i < nums1.size(); ++i) {
if(nums2.size()>0)
while (read2Num<nums2.size() && nums2[read2Num] < nums1[i]) {
++read2Num;
if (read1Num + read2Num >= selIdx && selNum > 0){
cacheNum += nums2[read2Num - 1];
--selNum;
if (selNum <= 0)
break;
}
}
++read1Num;
if (read1Num + read2Num >= selIdx && selNum > 0) {
cacheNum += nums1[i];
--selNum;
}
if (selNum <= 0)
break;
}
if(selNum>0)
for (int i = read2Num; i < nums2.size(); ++i) {
++read2Num;
if (read1Num + read2Num >= selIdx && selNum > 0) {
cacheNum += nums2[read2Num - 1];
--selNum;
if (selNum <= 0)
break;
}
}
return cacheNum/calNum;
}
leetcode上最快的示例代码:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size();
int n = nums2.size();
int l = m+n;
int a = findK(nums1, 0, nums2, 0, (l+1)/2);
int b = findK(nums1, 0, nums2, 0, (l+2)/2);
cout<<a<<endl;
cout<<b<<endl;
return (a+b)/2.0;
}
int findK(vector<int>& nums1, int s1, vector<int>& nums2, int s2, int k)
{
if(s1==nums1.size()) return nums2[s2+k-1];
if(s2==nums2.size()) return nums1[s1+k-1];
if(k==1) return min(nums1[s1], nums2[s2]);
int m1 = s1+k/2-1<nums1.size() ? nums1[s1+k/2-1]:INT_MAX;
int m2 = s2+k/2-1<nums2.size() ? nums2[s2+k/2-1]:INT_MAX;
if(m1<m2)
{
return findK(nums1, s1+k/2, nums2, s2, k - k/2);
}else
{
return findK(nums1, s1, nums2, s2+k/2, k - k/2);
}
}
代码思路:
利用二分的思想,每次在两个vector中查找第k个数,分别取两个vector的中位数进行比较,对数值较小的那个进行规模缩减,每次都丢弃了k/2的个数,k是1 或者 nums1丢弃到尾端或者nums2丢弃到尾端,可以计算得到目标值。