C#实现寻找两个正序数组的中位数

给定两个大小分别为 m 和 n 的正序(从小到大)数组nums1 和nums2。请你找出并返回这两个正序数组的 中位数 。

算法的时间复杂度应该为 O(log (m+n)) 。

示例 1:

输入:nums1 = [1,3], nums2 = [2]输出:2.00000解释:合并数组 = [1,2,3] ,中位数 2

示例 2:

输入:nums1 = [1,2], nums2 = [3,4]输出:2.50000解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5


具体代码 :

public class Solution {

    public double FindMedianSortedArrays(int[] nums1, int[] nums2) {

          if (nums1.Length > nums2.Length)

            return FindMedianSortedArrays(nums2, nums1); // Ensure nums1 is the smaller array

        int x = nums1.Length;

        int y = nums2.Length;

        int low = 0;

        int high = x;

        while (low <= high)

        {

            int partitionX = (low + high) / 2;

            int partitionY = (x + y + 1) / 2 - partitionX;

            int maxLeftX = (partitionX == 0) ? int.MinValue : nums1[partitionX - 1];

            int minRightX = (partitionX == x) ? int.MaxValue : nums1[partitionX];

            int maxLeftY = (partitionY == 0) ? int.MinValue : nums2[partitionY - 1];

            int minRightY = (partitionY == y) ? int.MaxValue : nums2[partitionY];

            if (maxLeftX <= minRightY && maxLeftY <= minRightX)

            {

                if ((x + y) % 2 == 0)

                {

                    return ((double)Math.Max(maxLeftX, maxLeftY) + Math.Min(minRightX, minRightY)) / 2;

                }

                else

                {

                    return (double)Math.Max(maxLeftX, maxLeftY);

                }

            }

            else if (maxLeftX > minRightY)

            {

                high = partitionX - 1;

            }

            else

            {

                low = partitionX + 1;

            }

        }

    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容