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)).(有两个有序数组nums1和nums2,他们的长度分别是m,n,找到两个数组的中位数,并且时间复杂度为O(log(m+n))
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int keyPosition=0;
int SUM=nums1Size+nums2Size;
double answer=0;
if(SUM%2==0)
keyPosition=SUM/2;
else keyPosition=(SUM+1)/2;
int i=0,j=0,count=0;
bool flag=true;
bool flag1=true;
char c;
if(nums1Size==0)
{
if(SUM%2==0)
{
answer=(nums2[SUM/2]+nums2[SUM/2-1]);
answer/=2;
}
else answer=nums2[SUM/2];
return answer;
}
else if(nums2Size==0)
{
if(SUM%2==0)
{
answer=(nums1[SUM/2]+nums1[SUM/2-1]);
answer/=2;
}
else answer=nums1[SUM/2];
return answer;
}
while(flag)
{
while(flag1&&i<nums1Size&&j<nums2Size&&nums1[i]<=nums2[j])
{
i++;
count++;
if(count==keyPosition)
{
c='i';
flag=false;
flag1=false;
break;
}
}
while(flag1&&j<nums2Size&&i<nums1Size&&nums2[j]<=nums1[i])
{
j++;
count++;
if(count==keyPosition)
{
c='j';
flag=false;
flag1=false;
break;
}
}
if(i==nums1Size)
{
if(SUM%2==0)
{
if(!flag)
{
answer=nums1[i-1]+nums2[j];
answer/=2;
}
else
{
answer=(nums2[keyPosition-count-1+j]+nums2[keyPosition-count+j]);
answer/=2;
}
}
else
{
if(!flag)
answer=nums1[i-1];
else answer=nums2[keyPosition-count-1+j];
}
return answer;
}
else if(j==nums2Size)
{
if(SUM%2==0)
{
if(!flag)
{
answer=nums2[j-1]+nums1[i];
answer/=2;
}
else
{
answer=(nums1[keyPosition-count-1+i]+nums1[keyPosition-count+i]);
answer/=2;
}
}
else
{
if(!flag)
answer=nums2[j-1];
else answer=nums1[keyPosition-count-1+i];
}
return answer;
}
}
if(SUM%2==0)
{
if(c=='i')
{
answer=(nums1[i-1]+(nums1[i]<nums2[j]?nums1[i]:nums2[j]));
answer/=2;
}
else
{
answer=(nums2[j-1]+(nums2[j]<nums1[i]?nums2[j]:nums1[i]));
answer/=2;
}
}
else
{
if(c=='i')
answer=nums1[i-1];
else
answer=nums2[j-1];
}
return answer;
}