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)).数组Example 1: nums1 = [1, 3] nums2 = [2]code
The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4]it
The median is (2 + 3)/2 = 2.5io
复杂度
O(lg(m + n))class
思路
由于要找中位数,又是在两个sorted的数组里面。因此考虑用二分法。(二分法常常适合sorted的array).
接下来考虑如何二分。
假设第k个数是咱们要找的中位数,那么前k-1个数应该都比这个第k个数要小。后面的数都比这个第k个数大。(像变形的用二分法找第K个数)。
若是咱们每次在a数组中找前(k/2) = m个数,在b数组中找剩下的(k-k/2) = n个数。而后对a[p + k/2 - 1]和b[q + k - k/2 -1]进行比较,记为a[i]和b[j]。搜索
一直搜索到何时为止呢?
k=1表明的是,当前的这个是就是咱们想要的值,咱们应该在如何选择? Math.min(a[p], b[q]).im
if(a[i] < b[j]) { search(a[right], b[0], k - m); } else { search (a[0], b[right], k - n); }
咱们从找第K个数开始,一直到K=1,每次扔掉一部分数 k /2,因此时间复杂度是log(k).
K=(M + N) / 2, 因此时间复杂度是log(m + n)sort
代码di
class Solution { // 其实找的是第k个值。 public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len = nums1.length + nums2.length; if(len % 2 == 0) { return findKthNumberInTwoArray(nums1, nums2, 0, 0, len / 2) / 2 + findKthNumberInTwoArray(nums1, nums2, 0, 0, len / 2 + 1) / 2; } else { return findKthNumberInTwoArray(nums1, nums2, 0, 0, len / 2 + 1); } } // p is the start index of nums1, q is the start index of nums2, we wanna find the kth number // in both num1 & nums2 public double findKthNumberInTwoArray(int[] nums1, int[] nums2, int p, int q, int k) { if(p >= nums1.length) return nums2[q + k - 1]; if(q >= nums2.length) return nums1[p + k - 1]; if(k == 1) return Math.min(nums1[p], nums2[q]); int m = k / 2, n = k - m; // 由于当a数组没有中这个数的时候,说明第k必定在b数组剩余的数中和a数组的剩余数组中的一个。 int aVal = Integer.MAX_VALUE, bVal = Integer.MAX_VALUE; if(p + m - 1 < nums1.length) aVal = nums1[p + m - 1]; if(q + n - 1 < nums2.length) bVal = nums2[q + n - 1]; if(aVal < bVal) { return findKthNumberInTwoArray(nums1, nums2, p + m, q, k - m); } else { return findKthNumberInTwoArray(nums1, nums2, p, q + n, k - n); } } }