Leetcode: Median of Two Sorted Arrays

本文介绍了一种高效算法,用于查找两个已排序数组中的中位数,整体时间复杂度达到O(log(m+n))。通过利用数组已排序的特性,避免了合并数组所需的额外空间与时间开销。

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

Median of Two Sorted Arrays

 

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

Idea: The trivial solution is to consolidate these two sorted arrays and then find the median, then the time complexity is O(m+n) and we also need the extra space. Is there any way to utilize the properties of these two arrays: "sorted"? Tje answer is YES. A helper function will be created: findKthFromTwoSortedArrays(int A[], int starta, int enda, int B[], int startb, int endb, int k) ---- to find the k-th element from two sorted arrays. 

class Solution {
public:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        int mid = m+n;
        if( mid%2 == 0) {
            return (findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2) + 
                    findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2+1))/2.0;
        }
        else {
            return findKthFromTwoSortedArrays(A, 0, m, B, 0, n, mid/2+1);
        }
    }
    
    double findKthFromTwoSortedArrays(int A[], int starta, int enda, 
                                      int B[], int startb, int endb, int k) {
        if(starta == enda) {
            return B[startb+k-1];
        }
        
        if(startb == endb) {
            return A[starta+k-1];
        }
        if(k == 1) return std::min(A[starta], B[startb]);
        
        int mid = k/2;
        int min_len = std::min(enda-starta, endb-startb);
        mid = std::min(mid, min_len);
        if(A[starta+mid-1] > B[startb+mid-1]) {
            return findKthFromTwoSortedArrays(A, starta, enda, 
                                              B, startb+mid, endb, k-mid);
        }
        else {
            return findKthFromTwoSortedArrays(A, starta+mid, enda, 
                                              B, startb, endb, k-mid);
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值