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))所以几乎可以肯定是递归和分治的思想。
《算法导论》里有找两个数组第K小数的算法,时间复杂度为O(log(m+n)),所以直接调用即可
参考链接:http://blog.csdn.net/yutianzuijin/article/details/11499917/
Java参考代码:
public class Solution {
public static double findKth(int[] nums1, int index1, int[] nums2,
int index2, int k) {
if (nums1.length - index1 > nums2.length - index2)
return findKth(nums2, index2, nums1, index1, k);
if (nums1.length - index1 == 0)
return nums2[index2 + k - 1];
if (k == 1)
return Math.min(nums1[index1], nums2[index2]);
int p1 = Math.min(k / 2, nums1.length - index1), p2 = k - p1;
if (nums1[index1 + p1 - 1] < nums2[index2 + p2 - 1])
return findKth(nums1, index1 + p1, nums2, index2, k - p1);
else if (nums1[index1 + p1 - 1] > nums2[index2 + p2 - 1])
return findKth(nums1, index1, nums2, index2 + p2, k - p2);
else
return nums1[index1 + p1 - 1];
} static public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if ((nums1.length + nums2.length) % 2 != 0)
return findKth(nums1, 0, nums2, 0,
(nums1.length + nums2.length) / 2 + 1);
else
return findKth(nums1, 0, nums2, 0,
(nums1.length + nums2.length) / 2)
/ 2.0
+ findKth(nums1, 0, nums2, 0,
(nums1.length + nums2.length) / 2 + 1) / 2.0;
}
}
C++实现如下:
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
private:
double findKth(vector<int> nums1, int index1, vector<int> nums2, int index2, int k) {
if (nums1.size() - index1 > nums2.size() - index2) {
swap(nums1, nums2);
swap(index1,index2);
}
if (nums1.size() - index1 == )
return nums2[index2 + k - ];
if (k == )
return min(nums1[index1], nums2[index2]);
int p1 = min(k / , (int)nums1.size() - index1), p2 = k - p1;
if (nums1[index1 + p1 - ] < nums2[index2 + p2 - ])
return findKth(nums1, index1 + p1, nums2, index2, k - p1);
else if (nums1[index1 + p1 - ] > nums2[index2 + p2 - ])
return findKth(nums1, index1, nums2, index2 + p2, k - p2);
else
return nums1[index1 + p1 - ];
} public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if ((nums1.size() + nums2.size()) &)
return findKth(nums1, , nums2, ,
(nums1.size() + nums2.size()) / + );
else
return findKth(nums1, , nums2, ,(nums1.size() + nums2.size()) / )/ 2.0
+ findKth(nums1, , nums2, ,(nums1.size() + nums2.size()) / + ) / 2.0;
}
};