本文首发于每日一题:4 - 咸鱼Blog
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be .
Example 1
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints
-
nums1.legnth == m
-
nums2.legnth == n
-
0 <= m <=1000
-
0 <= n <= 1000
-
1 <= m+n <= 2000
-
Solution code
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
int sum=nums2Size+nums1Size;
int nums3[MAX+MAX]={0};
int re=sum%2;
int index=0;
int a1=0,a2=0;
while(a1<nums1Size&&a2<nums2Size){
if(nums1[a1]<nums2[a2])nums3[index++]=nums1[a1++];
else(nums1[a1]>nums2[a2])nums3[index++]=nums2[a2++];
}
while(a1<nums1Size)nums3[index++]=nums1[a1++];
while(a2<nums2Size)nums3[index++]=nums2[a2++];
if(re){
index=(sum-re)/2;
return (double)nums3[index];
}
else{
index=sum/2;
return ((double)nums3[index]+(double)nums3[index-1])/2.0;
}
}
Note:
-
这题需要寻找中位数,要求的时间复杂度为O(log(M+N),相当于将两个给定的数组遍历一遍;
-
可以真正生成一个新数组,是两个数组的归并,像上面代码示例,也可以标记的形式,获取对应数字即可,在源代码中有;
-
只需要针对大小进行指针的前进选择,到达对应位置即可找到;
-
需要分奇数偶数进行输出;
-
输出结果是五位小数的
double。
该博客讨论了一个算法问题,即如何在O(log(M+N))的时间复杂度内找到两个已排序数组的中位数。提供的解决方案是通过合并两个数组并找到中间元素,考虑数组长度为奇数和偶数的情况。此问题考察了数组操作和中位数计算的效率。
670

被折叠的 条评论
为什么被折叠?



