Leetcode[4] Median of two sorted arrays

Leetcode[4] Median of two sorted arrays

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

Binary search

复杂度
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]。搜索

  • a[i] < b[j]: 说明咱们能够扔掉0-i之间的(i+ 1)个数。为何?
    由于a数组中的前m个数的最大值都比b数组中的前n个数要小,那么这前m个数必定是在咱们想要的中位数以前的,而且对找到中位数没有说明影响。因此为了缩小搜索范围,咱们能够扔掉这些数,在a的剩下来的数中和b的数组中接着找。
  • i>=a.length: 说明a中没有m个数能够寻找。那么第K个数要么在b剩下的数组[n ~ b.length]中,要么就在a的前m个数中。

一直搜索到何时为止呢?
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);
        }
    }
}
相关文章
相关标签/搜索