Java实现Leetcood --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)).

首先想到的是最笨的方法,将两个数组拼接在一起,然后排序,取中间位。结果,,通过了,,,
但是速度不理想啊
Java中如果需要对一个collections排序,需要继承于Comparable或者comparator接口,那么使用的排序算法是什么呢,一般情况下,排序算法包括:插入排序、快速排序、合并排序、冒泡排序等,java的Collections.sort算法调用的是合并排序,它是稳定排序,当数据接近有序的时候,效率更高。
时间复杂度为:归并排序的最好、最坏和平均时间复杂度都是O(nlogn)
这里写图片描述
代码如下:

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        ArrayList<Integer> List = new ArrayList<Integer>();
        for(int i = 0;i<nums1.length;i++){
            List.add(nums1[i]);
        }
        for(int j = 0;j<nums2.length;j++){
            List.add(nums2[j]);
        }
        Collections.sort(List);
        int n = nums1.length+nums2.length;
        if(n%2 == 0){
            return (List.get(n/2)+List.get(n/2-1))/2.0;
        }else{
            return List.get(n/2);
        }
    }
}

所以要进行优化
我们注意一句话:two sorted arrays nums1 and nums2
那么我们可以借鉴如下一种方法:

 import static java.lang.Math.*;
public class Solution {
    public double findMedianSortedArrays(int[] A, int[] B) {
      int n = A.length;
    int m = B.length;
    // the following call is to make sure len(A) <= len(B).
    // yes, it calls itself, but at most once, shouldn't be
    // consider a recursive solution
    if (n > m)
        return findMedianSortedArrays(B, A);

    // now, do binary search
    int k = (n + m - 1) / 2;
    int l = 0, r = Math.min(k, n); // r is n, NOT n-1, this is important!!
    while (l < r) {
        int midA = (l + r) / 2;
        int midB = k - midA;
        if (A[midA] < B[midB])
            l = midA + 1;
        else
            r = midA;
    }

    // after binary search, we almost get the median because it must be between
    // these 4 numbers: A[l-1], A[l], B[k-l], and B[k-l+1] 

    // if (n+m) is odd, the median is the larger one between A[l-1] and B[k-l].
    // and there are some corner cases we need to take care of.
    int a = Math.max(l > 0 ? A[l - 1] : Integer.MIN_VALUE, k - l >= 0 ? B[k - l] : Integer.MIN_VALUE);
    if (((n + m) & 1) == 1)
        return (double) a;

    // if (n+m) is even, the median can be calculated by 
    //      median = (max(A[l-1], B[k-l]) + min(A[l], B[k-l+1]) / 2.0
    // also, there are some corner cases to take care of.
    int b = Math.min(l < n ? A[l] : Integer.MAX_VALUE, k - l + 1 < m ? B[k - l + 1] : Integer.MAX_VALUE);
    return (a + b) / 2.0;
}

}

其实速度差不多,,,515ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值