leetcode 4. Median of Two Sorted Arrays O(log(m+n))解法

4. Median of Two Sorted Arrays

 

Question Editorial Solution
  My Submissions
  • Total Accepted: 111263
  • Total Submissions: 563486
  • Difficulty: Hard

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]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5















普通O(m+n)解法,归并

我开始看到这个题,直接想到这个简单解法,写完也通过了。
思路:把两个数组都是从头开始归并,直到两个数组长度的中间值mid+1。到mid+1而不是Mid是由于有个是否长度是偶数的区别。同时判断数组别越界
public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        int mid = (l1+l2)/2;
        int[] s = new int[mid+1];
        int j=0,k=0;
        for(int i=0;i=l2||nums1[j]

O(log(m+n))解法,转换为求两个排序数组 第 k 大的值 问题

思路一:这个解法大概思路很简单,就是A数组的中间元素与B数组的中间元素相比较,从而删掉较小元素所在数组的前一半和较大元素所在数组的后一半。
思路二:同样,就是A数组的中间元素与B数组的中间元素相比较,从而删掉较小元素所在数组的前一半和较大元素所在数组的后一半。
这里按照思路一:
具体解释:http://www.07net01.com/2015/07/871155.html
public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length, n = nums2.length;
        int k = (m + n) / 2;
        if((m+n)%2==0){
            return (findKth(nums1,nums2,0,0,m,n,k)+findKth(nums1,nums2,0,0,m,n,k+1))/2;
        }   else {
            return findKth(nums1,nums2,0,0,m,n,k+1);
        }

    }

    private double findKth(int[] arr1, int[] arr2, int start1, int start2, int len1, int len2, int k){
        if(len1>len2){
            return findKth(arr2,arr1,start2,start1,len2,len1,k);
        }
        if(len1==0){
            return arr2[start2 + k - 1];
        }
        if(k==1){
            return Math.min(arr1[start1],arr2[start2]);
        }
        int p1 = Math.min(k/2,len1) ;
        int p2 = k - p1;
        if(arr1[start1 + p1-1]arr2[start2 + p2-1]){
            return findKth(arr1,arr2,start1,start2 + p2,len1,len2-p2,k-p2);
        } else {
            return arr1[start1 + p1-1];
        }
    }
}












你可能感兴趣的:(leetcode)