LeetCode4. Median of Two Sorted Arrays

一、题目描述

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
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5


二、思路

这是一个很经典的Divide & Conquer的题目,关键就在如何划分。(分治算法)

问题大致描述:如何在给定的两个有序数组里面找其中的中值,或者变形问题,如何在2个有序数组数组中查找Top K的值(Top K的问题可以转换成求第k个元素的问题)。这个算法在很多实际应用中都会用到,特别是在当前大数据的背景下。

参考博客,解释得很详细,本文解法由该博客提供


三、程序

C#程序,供参考。

class Program
{
    public static double FindMedianSortedArrays(int[] nums1, int[] nums2)
    {
        int n = nums1.Length;
        int m = nums2.Length;
        if (n > m)
        {
            return FindMedianSortedArrays(nums2, nums1);
        }

        int l1=int.MinValue, l2=int.MinValue, r1=int.MaxValue, r2=int.MaxValue, c1, c2, start = 0, end = n * 2;
        while (start <= end)
        {
            c1 = (start + end) / 2;
            c2 = n + m - c1;
            l1 = (c1 == 0) ? int.MinValue : nums1[(c1 - 1) / 2];
            r1 = (c1 == n * 2) ? int.MaxValue : nums1[c1 / 2];
            l2 = (c2 == 0) ? int.MinValue : nums2[(c2 - 1) / 2];
            r2 = (c2 == m * 2) ? int.MaxValue : nums2[c2 / 2];

            if (l1 > r2)
            {
                end = c1 - 1;
            }
            else if (l2 > r1)
            {
                start = c1 + 1;
            }
            else
            {
                break;                    
            }
        }

        return (Math.Max(l1, l2) + Math.Min(r1, r2)) / 2.0;

    }

    static void Main(string[] args)
    {
        int[] numArr1 = new[] {1, 2};
        int[] numArr2 = new[] {3, 4};
        double result = FindMedianSortedArrays(numArr1, numArr2);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值