首页 > Java > java教程 > 正文

在 Java 中查找两个排序数组的中位数

WBOY
发布: 2024-07-22 17:46:23
原创
1035 人浏览过

Finding the Median of Two Sorted Arrays in Java

JAVA教程
Java 文件

介绍

求两个排序数组的中位数的问题是一个经典的编程面试问题。挑战在于有效地找到中位数,时间复杂度为 O(log(min(m, n))),其中 m 和 n 是两个数组的大小。在本文中,我们将介绍一个使用二分搜索来实现这种效率的 Java 解决方案。

问题陈述

给定两个排序数组 nums1 和 nums2,找到这两个排序数组的中位数。整体运行时复杂度应为 O(log(min(m, n))),其中 m 和 n 是两个数组的大小。

方法

为了解决这个问题,我们对两个数组中较小的一个使用二分搜索方法。目标是对两个数组进行分区,使左半部分包含小于或等于右半部分元素的所有元素。以下是分步说明:

  1. 确保 nums1 是较小的数组:为了更容易进行二分查找,请确保 nums1 是较小的数组。
  2. 执行二分查找:对 nums1 使用二分查找来找到正确的分区。
  3. 分区:对两个数组进行分区,使左侧包含较低的元素,右侧包含较高的元素。
  4. 计算中位数:根据分区,计算中位数。

解决方案

这是该解决方案的详细 Java 实现:

public class MedianOfTwoSortedArrays {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        // Ensure nums1 is the smaller array
        if (nums1.length > nums2.length) {
            int[] temp = nums1;
            nums1 = nums2;
            nums2 = temp;
        }

        int x = nums1.length;
        int y = nums2.length;
        int low = 0, high = x;

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

            // Edge cases
            int maxX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];
            int minX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX];
            int maxY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];
            int minY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY];

            if (maxX <= minY && maxY <= minX) {
                // Correct partition
                if ((x + y) % 2 == 0) {
                    return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2.0;
                } else {
                    return Math.max(maxX, maxY);
                }
            } else if (maxX > minY) {
                high = partitionX - 1;
            } else {
                low = partitionX + 1;
            }
        }

        throw new IllegalArgumentException("Input arrays are not sorted");
    }

    public static void main(String[] args) {
        MedianOfTwoSortedArrays solution = new MedianOfTwoSortedArrays();

        int[] nums1 = {1, 3};
        int[] nums2 = {2};
        System.out.println("Median: " + solution.findMedianSortedArrays(nums1, nums2)); // Output: 2.0

        int[] nums1_2 = {1, 2};
        int[] nums2_2 = {3, 4};
        System.out.println("Median: " + solution.findMedianSortedArrays(nums1_2, nums2_2)); // Output: 2.5
    }
}
登录后复制

解释

  1. 初始化:确保nums1是较小的数组。
  2. 二分查找:对nums1执行二分查找以找到正确的分区。
  3. 划分和中位数计算:计算左侧元素的最大值和右侧元素的最小值,以求中位数。

结论

这种二分搜索方法提供了一种有效的解决方案来查找两个排序数组的中位数。通过在较小的数组上利用二分搜索,该解决方案实现了 O(log(min(m, n))) 的时间复杂度,使其适合大型输入数组。

以上是在 Java 中查找两个排序数组的中位数的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!