LeetCode 算法第四题

本文介绍了一种在O(log(m+n))的时间复杂度内找到两个有序数组中位数的方法。通过调整两个数组的指针位置,最终确定中位数的位置。此算法适用于不同长度的两个有序数组。

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

Description

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

Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Code

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    int n = (nums1Size >= nums2Size) ? nums1Size : nums2Size;
    int m = nums1Size + nums2Size - n;
    int *sn = (nums1Size >= nums2Size) ? nums1 : nums2;
    int *sm = (nums1Size < nums2Size) ? nums1 : nums2;
    int imin, imax, i, j, ihalf, max_left, min_right;
    imin = 0; imax = m; ihalf = (m + n + 1)/2;
    while(imin <= imax){
        i=(imin + imax)/2;
        j=ihalf-i;
        if(i<m && sn[j-1]>sm[i])
            imin = i+1;
        else if(i > 0 && sm[i-1]>sn[j])
            imax = i-1;
        else{
            if(i == 0)
                max_left = sn[j-1];
            else if(j == 0)
                max_left = sm[i-1];
            else
                max_left = (sn[j-1] > sm[i-1]) ? sn[j-1] : sm[i-1];

            if((m+n)%2 == 1)
                return max_left;

            if(i == m)
                min_right = sn[j];
            else if(j == n)
                min_right = sm[i];
            else
                min_right = (sn[j] < sm[i]) ? sn[j] : sm[i];

            return (min_right + max_left)/2.0;
        }
    }
    return 0;
}

Reference

@MISSMARY的分析

Discussion

  1. Understand the definition and find out the essential need of the problem.
  2. pseudo-code
  3. special cases analysis
  4. coding
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值