标签:求两个有序数组的中位数
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find themedian of the two sorted arrays. The overall run time complexity should beO(log (m+n)).
若m+n为奇数则中位数(median)排好序后的中间值,若为偶数则中位数只的是中间两个数的平均值。
题目中要求时间复杂度为O(log(m+n)),显然可以用分治的思想求解。
int findKth(vector<int>&num1, int begin1, int end1, vector<int> &num2, int begin2, intend2, int k); doubleSolution::findMedianSortedArrays(vector<int> &num1, vector<int>&num2) { int m = num1.size(); int n = num2.size(); if ((m + n) & 0x1) { return findKth(num1, 0, m - 1,num2, 0, n - 1, (m + n) / 2); } else { return (findKth(num1, 0, m - 1,num2, 0, n - 1, (m + n) / 2 - 1) + findKth(num1, 0, m - 1,num2, 0, n - 1, (m + n) / 2)) / 2.0; } } int findKth(vector<int>&num1, int begin1, int end1, vector<int> &num2, int begin2, intend2, int k) { int m = end1 - begin1 + 1; int n = end2 - begin2 + 1; if (m > n) { return findKth(num2, begin2, end2,num1, begin1, end1, k); } if (0 == m) { return num2[begin2 + k]; } if (0 == k) { return min(num1[begin1],num2[begin2]); } int middle1 = min((begin1 + end1) / 2, k +begin1); int middle2 = begin2 + (k - (middle1 -begin1 + 1)); if (middle2 < begin2) { ++middle2; --middle1; } if (num1[middle1] < num2[middle2]) { return findKth(num1, middle1 + 1,end1, num2, begin2, end2, k - (middle1 - begin1 + 1)); } else if (num1[middle1] > num2[middle2]) { return findKth(num1, begin1, end1,num2, middle2 + 1, end2, k - (middle2 - begin2 + 1)); } else { return num1[middle1]; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:求两个有序数组的中位数
原文地址:http://blog.csdn.net/woniu317/article/details/47785935