題目:
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
思路:
由於數組是已經排序好的數組,則直接合並數組,然後根據兩數組總的元素個數之和,獲得中間數字。其中可以做一些優化。
C語言代碼:
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
double result =0;
int sumSize = nums1Size + nums2Size;
int len = sumSize / 2;
int size =len+1;
int * merge =(int *)malloc (size * sizeof(int));
int i,n1,n2;
for(i=0,n1 =0 ,n2 =0 ; i < size ; i++)
{
if(n1<nums1Size && n2<nums2Size)
{
if(nums1[n1] > nums2[n2])
{
merge[i] = nums2[n2];
n2++;
}else
{
merge[i] =nums1[n1];
n1++;
}
}
else if(n1 >= nums1Size)
{
merge[i] = nums2[n2];
n2++;
}
else if(n2 >= nums2Size)
{
merge[i] =nums1[n1];
n1++;
}
}
if(sumSize %2 !=0)
{
result= merge[len];
}
else
{
result = merge[len-1] + merge[len];
result = result /2;
}
return result;
}
效率:
Leecode中同一代碼執行的時間可能不同。本系列中,取代碼最佳效率。