Algorithm twenty days
seventh day
Find the median of two ordinal arrays
Given two arrays, find the median after merging. The required time complexity is log(m+n);
/ Example cin>>nums1=[1,3],nums2=[2]
cout<<2.00000
Explanation: merge arrays to find the median; /
This question reflects the importance of the foundation. When writing binary merge sorting, I wrote the function of merging. When I saw the question, I immediately reacted:
#include<bits/stdc++.h>
using namespace std;
vector<int> HeBing(vector<int> &a,vector<int> &b)
{
vector<int> temp;
int i=0,j=0;
while(i<a.size()&&j<b.size())
{
if(a[i]>=b[j])
{
temp.push_back(b[j]);
j++;
}
else
{
temp.push_back(a[i]);
i++;
}
}
while(i<a.size())
{
temp.push_back(a[i]);
i++;
}
while(j<b.size())
{
temp.push_back(b[j]);
j++;
}
return temp;
}
double Mid(vector<int> &temp)
{
if(1&temp.size())//判断奇数还是偶数个
return temp[temp.size()/2];
else
return (double)(temp[temp.size()/2]+temp[temp.size()/2-1])/2;
}
int main()
{
vector<int> a={
1,2};
vector<int> b={
3,4};
vector<int> temp=HeBing(a,b);
printf("%0.5f",Mid(temp));
}
The time complexity does not meet the requirements of the title, I will write it tomorrow. When I
saw the log, I thought of using the dichotomy method. How can this be dichotomized? First of all, the median is the number in the middle, so we only need to find a number that is the kth number and use the dichotomy method to divide the problem into two: that is, find the 5th smallest number among all elements
of arrays a and b, then when a [k/2-1]<b[k/2-1] can exclude the kth smallest number is a[k/2-1] and before, because a[k/2-1] and the number before At most k/2+k/2-1, (when b[k/2-1] and the previous numbers are less than a[k/2-1]), at this time two elements are excluded, then now It is necessary to obtain the kk/2th largest number among the remaining elements. Until k==1, it will not be able to end at the end. For even numbers, just find a k+1th largest number
#include<bits/stdc++.h>
using namespace std;
int f(vector<int> &nums1,vector<int> &nums2,int k)
{
int m=nums1.size();
int n =nums2.size();
int index1=0,index2=0;
while(true)
{
if(index1==m)
return nums2[index2+k-1];
if(index2==n)
return nums1[index1+k-1];
if(k==1)
return min(nums1[index1],nums2[index2]);
int i=min(index1+k/2-1,m-1);
int j=min(index2+k/2-1,n-1);
int pivot1=nums1[i];
int pivot2=nums2[j];
if(pivot1<=pivot2)
{
k-=i-index1+1;
index1=i+1;
}
if(pivot1>pivot2)
{
k-=j-index2+1;
index2=j+1;
}
}
}
double m(vector<int> &nums1,vector<int> &nums2)
{
int length=nums1.size()+nums2.size();
if(length%2==1)//判断奇偶
return f(nums1,nums2,(length+1)/2);
else
return (f(nums1,nums2,length/2)+f(nums1,nums2,length/2+1))/2.0;
}
int main()
{
vector<int> a={
1,2};
vector<int> b={
3,4};
double temp=m(a,b);
printf("%0.5f",temp);
}
Time complexity O(log(m+n));