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)).
两个排序好的数组,能想到的最好的方法是把两个数组合并起来,然后用一种效率最好的算法排序,然后计算出中间的数字。当然这种算法,时间复杂度,达不到 O(log(m+n)) 但是,既然只能想到这种方法,也试着提交一下,居然还accepted了。
void quickSort(int *num, int left, int right){
if (left >= right)
return;
int tmp = num[left];
int i = left, j = right;
while (i < j){
while (num[j] >= tmp && i < j)
j--;
num[i] = num[j];
while (num[i] < tmp && i < j)
i++;
num[j] = num[i];
}
num[i] = tmp;
quickSort(num, left, i);
quickSort(num, j+1, right);
}
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int *result = (int *)malloc(sizeof(int)*(nums1Size+nums2Size));
memcpy(result, nums1, sizeof(int)*nums1Size);
memcpy(result+nums1Size, nums2, sizeof(int)*nums2Size);
quickSort(result, 0, nums1Size+nums2Size-1);
if (nums1Size+nums2Size == 1)
return result[0];
if ((nums1Size+nums2Size)%2 == 1)
return (double)result[(nums1Size+nums2Size)/2];
if ((nums1Size+nums2Size)%2 == 0)
return (double)(result[(nums1Size+nums2Size)/2-1] + result[(nums1Size+nums2Size)/2])/2.0;
}
在我看了标签以后,才恍然大悟,两个排序好的数组,就应该想到分治法啊,并且还要求时间复杂度达到 O(log(m+n)) 还有什么算法能够达到这个效果呢。