【面试题】【C语言】寻找两个正序数组的中位数

寻找两个正序数组的中位数

仅供学习

题目

在这里插入图片描述


算法时间复杂度

二分查找算法,时间复杂度为 O(log(min(m, n))),其中 m 和 n 分别是两个数组的长度。

子函数

查找两个数字的最大值

int max(int a, int b) {
    return a > b ? a : b;
}

查找两个数字的最小值

int min(int a, int b) {
    return a < b ? a : b;
}

findMedianSortedArrays

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    // Ensure nums1 is the smaller array
    if (nums1Size > nums2Size) {
        return findMedianSortedArrays(nums2, nums2Size, nums1, nums1Size);
    }

    int x = nums1Size;
    int y = nums2Size;
    int low = 0;
    int high = x;

    while (low <= high) {
        int partitionX = (low + high) / 2;
        int partitionY = (x + y + 1) / 2 - partitionX;

        int maxX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1];
        int minX = (partitionX == x) ? INT_MAX : nums1[partitionX];

        int maxY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1];
        int minY = (partitionY == y) ? INT_MAX : nums2[partitionY];

        if (maxX <= minY && maxY <= minX) {
            // We have partitioned array at the correct place
            // Now we get max of left elements and min of right elements to get the median in case of even length combined array size
            if ((x + y) % 2 == 0) {
                return ((double)max(maxX, maxY) + min(minX, minY)) / 2;
            } else {
                return (double)max(maxX, maxY);
            }
        } else if (maxX > minY) { // we are too far on the right side for partitionX. Go on left side.
            high = partitionX - 1;
        } else { // we are too far on the left side for partitionX. Go on right side.
            low = partitionX + 1;
        }
    }

    // If we reach here, it means the arrays are not sorted
    fprintf(stderr, "Input arrays are not sorted or there is some other error.\n");
    return -1;
}

说明

  • 该代码实现了一个查找两个正序数组中位数的算法,使用了二分查找法来优化时间复杂度。
  • findMedianSortedArrays 函数首先确保第一个数组(nums1)是较小的一个,这样可以减小搜索范围。
  • 在 while 循环中,通过二分查找确定两个数组的分割点,使得分割后的左半部分和右半部分元素数量接近。
  • 根据分割点计算最大左边元素和最小右边元素,进而确定中位数。
  • 主函数通过示例数据验证了算法的正确性。
  • 17
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq2108462953

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值