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 + findKth(nums1, 0, nums2, 0, (nums1.length + nums2.length) / 2 + 1) / 2; } }
Java for LeetCode 004 Median of Two Sorted Arrays
原文:http://www.cnblogs.com/tonyluis/p/4451870.html