Leetcode(java) 4. Median of Two Sorted Arrays

Q:

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

The overall run time complexity should be O(log (m+n)).

A:

It can be converted to the problem of finding the kth number in the two sorted arrays.

  • if (m+n)%2==1, k= (m+n)/2
  • if (m+n)%2==0, k1= (m+n)/2  and k2 = (m+n)/2 -1, res = ([k1]+[k2])*0.5

Then, how to find the kth number?

We can compare the k/2-th numbers in array1 and arrary2.

  • if array1[k/2] > array2[k/2], array1 = array1[ 0...k/2]  array2 = array2[k/2+1,n]
  • if array1[k/2] < array2[k/2], array1 = array1[k/2+1,n]  array2 = array2[ 0...k/2]
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        if((m+n)%2==0){
           
            return 0.5*( cal(nums1,nums2,(m+n)/2-1,0,m-1,0,n-1) + cal(nums1,nums2,(m+n)/2,0,m-1,0,n-1));
        }else{
            
           return cal(nums1,nums2,(m+n)/2,0,m-1,0,n-1);
        }
    }

    int cal(int[] nums1, int[] nums2, int k, int s1, int e1, int s2, int e2){
        if(s1>e1){
            return nums2[s2+k];
        }
        if(s2>e2){
            return nums1[s1+k];
        }
        if(k==0){
            return nums1[s1]<nums2[s2]?nums1[s1]:nums2[s2];
        }

        int mid1 = k*(e1-s1+1)/(e1-s1+1+e2-s2+1); //important
        int mid2 = k-mid1-1;

        mid1 += s1;
        mid2 += s2;

        if(nums1[mid1]<nums2[mid2]){
            k -= mid1-s1+1;
            s1 = mid1+1;
            e2 = mid2;
        }else{
            k -= mid2-s2+1;
            s2 = mid2+1;
            e1 = mid1;
        }

        return cal(nums1,nums2,k,s1,e1,s2,e2);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值