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

4. Median of Two Sorted Arrays

 

  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<mid+1;i++){
            if(j<l1&&(k>=l2||nums1[j]<nums2[k])){
                s[i]=nums1[j++];
            }else{
                s[i]=nums2[k++];
            }
        }
        if ((l1+l2)%2!=0){
            return (double)s[mid];
        }else{
            return (double)(s[mid-1]+s[mid])/2;
        }
    }
}

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 + p1,start2,len1-p1,len2,k-p1);
        } else 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];
        }
    }
}












  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值