2015年6月6日星期六

[LeetCode] Median of Two Sorted Arrays

Problem:

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 Code:


public class Solution {
    public double findMedianSortedArrays(int A[], int B[]) {
        if (A == null || B == null) {
            return 0.0;
        }
        if ((A.length + B.length) % 2 == 1) {
            return findKthElement(A, B, 0, 0, (A.length + B.length) / 2 + 1) + 0.0;
        } else {
            return (findKthElement(A, B, 0, 0, (A.length + B.length) / 2) + findKthElement(A, B, 0, 0, (A.length + B.length) / 2 + 1)) / 2.0;
        }
    }
    
    private double findKthElement(int[] A, int[] B, int A_start, int B_start, int k) {
        if (A_start >= A.length) {
            return B[B_start + k - 1];
        }
        if (B_start >= B.length) {
            return A[A_start + k - 1];
        }
        if (k == 1) {
            return Math.min(A[A_start], B[B_start]);
        }
        int eleA;
        if (A_start + k / 2 - 1 < A.length) {
            eleA = A[A_start + k / 2 - 1];
        } else {
            eleA = Integer.MAX_VALUE;
        }
        int eleB;
        if (B_start + k / 2 - 1 < B.length) {
            eleB = B[B_start + k / 2 - 1];
        } else {
            eleB = Integer.MAX_VALUE;
        }
        if (eleA >= eleB) {
            return findKthElement(A, B, A_start, B_start + k / 2, k - k / 2);
        } else {
            return findKthElement(A, B, A_start + k / 2, B_start, k - k / 2);
        }
    }
}

没有评论:

发表评论