LeetCode 4: Median Of Two Sorted Array

本文介绍了一种寻找两个有序数组中位数的方法,通过递归算法实现了O(log(m+n))的时间复杂度,提供了详细的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Difficulty: 5

Frequency: 3


Problem:

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)).


Solution:

class Solution {
public:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function;       
        if(((m+n)&1)==0)
        {
            return ((double)findKthInSortedArrayRecursive(A, m, B, n, (m+n)/2+1) + (double)findKthInSortedArrayRecursive(A, m, B, n, (m+n)/2))/2;
        }
        else
        {
            return findKthInSortedArrayRecursive(A, m, B, n, (m+n+1)/2);
        }
    }
    int findKthInSortedArrayRecursive(int A[], int m, int B[], int n, int k)
    {
        if (m == 0)
            return B[k-1];
        else if (n==0)
            return A[k-1];
        int i_place;
        if (m>n)
        {
            i_place = BinarySearchRecursive(A, 0, m - 1, B[n/2]);
            if (i_place + n/2 == k - 1)
                return B[n/2];
            else if (i_place + n/2 > k - 1)
                return findKthInSortedArrayRecursive(A, i_place, B, n/2, k);
            else
                return findKthInSortedArrayRecursive(&A[i_place], m-i_place, &B[n/2+1], n - n/2 - 1, k - i_place - n/2 - 1);
        }
        else
        {
            i_place = BinarySearchRecursive(B, 0, n - 1, A[m/2]);
            if (i_place + m/2 == k - 1)
                return A[m/2];
            else if (i_place + m/2 > k - 1)
                return findKthInSortedArrayRecursive(B, i_place, A, m/2, k);
            else
                return findKthInSortedArrayRecursive(&B[i_place], n-i_place, &A[m/2+1], m - m/2 - 1, k - i_place - m/2 - 1);
        }
    }
    // Return the index of target, if target were inserted into this array.
    int BinarySearchRecursive(int A[], int i_begin, int i_end, int target)
    {
        int i_middle = (i_begin+i_end)/2;
        if (target==A[i_middle])
            return i_middle;
        else if(i_begin==i_end)
        {
            if (target<A[i_middle])
                return i_middle;
            else
                return i_middle+1;
        }
        
        if (target<A[i_middle])
        {
            if (i_begin == i_middle)
                return i_begin;
            else
                return BinarySearchRecursive(A, i_begin, i_middle-1, target);
        }
        else
        {
            return BinarySearchRecursive(A, i_middle+1, i_end, target);
        }
    }
};


Notes:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值