Median of Two Sorted Arrays

这个题真的很简单,但是在LeetCode中难度排最高级,开始写代码进度跑的时候以为是题理解错啦,它的输出信息是

input:

ouput:

expected:

我以为第二项是正确答案,可恶的英文,最后知道原因后,就能写正确代码,但是中间老是有点改动就想提交,不知道这习惯好不,下面贴上丑陋的代码,花时间再看看别人的优秀代码。

double findMedianSortedArrays(int A[], int m, int B[], int n)
{
    int sum = m + n;
    if (sum == 0) {
        return 0;
    } else if (sum == 1) {
        return m > n ? A[m - 1] : B[n - 1];
    } else if(m == 0) {
        if (sum % 2 == 0) {
            return (B[sum / 2 - 1] + B[sum / 2]) / 2.f;
        } else {
            return B[sum / 2];
        }
    } else if (n == 0) {
        if (sum % 2 == 0) {
            return (A[sum / 2 - 1] + A[sum / 2]) / 2.f;
        } else {
            return A[sum / 2];
        }
    }
    int count = sum / 2;
    int j = 0, k = 0;
    int tmp1 = 0;
    for (int i = 0; i < count; i++) {
        if (j >= m || (k < n && A[j] > B[k])) {
            if (sum % 2 ==0) {
                tmp1 = B[k];
            }
            k++;
        } else {
            if (sum % 2 ==0) {
                tmp1 = A[j];
            }
            j++;
        }
    }
    float result = .0f;
    if (j >= m) {
        result = B[k];
    } else if(k >= n) {
        result = A[j];
    } else {
        result = A[j] < B[k] ? A[j] : B[k];
    }
    if (sum % 2 == 0) {
        return (tmp1 + result) / 2.f;
    } else {
        return result;
    }
}

 

posted on 2015-04-15 21:24  unreall  阅读(114)  评论(0编辑  收藏  举报

导航