[leet code 4] Median of Two Sorted Arrays

1 题目

There are two sorted arrays A and B 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)).

2 思路

这题比较简单,实现的其实就是归并排序merge那个部分。

3 代码

public class MedianOfTwoSortedArrays {
    public double findMedianSortedArrays(int A[], int B[]) {
        double median = 0;
        int sum = A.length + B.length;
        int[] C = new int[sum];
        int c = 0;
        int a = 0;
        int b = 0;
        while(a < A.length && b < B.length){
            if (A[a] > B[b]) {
                C[c] = B[b];
                b++;
                c++;
            }else {
                C[c] = A[a];
                a++;
                c++;
            }
        }
        while (a < A.length) {
            C[c] = A[a];
            c++;
            a++;
        }
        while(b < B.length){
            C[c] = B[b];
            c++;
            b++;
        }
        
        
        if (sum % 2 == 0) {
            median = (double) (C[sum/2] + C[sum/2 - 1])/2;
        }else {
            median = C[sum/2];
        }
        System.out.println(median);
        return median;
    }
原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4282564.html