LeetCode【4. 寻找两个正序数组的中位数】

快乐安康

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

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

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    if (nums1.length > nums2.length) {
        return findMedianSortedArrays(nums2, nums1);
    }
    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;

        int maxX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];
        int maxY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];

        int minX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX];
        int minY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY];

        if (maxX <= minY && maxY <= minX) {
            if ((x + y) % 2 == 0) {
                return (double) (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2;
            } else {
                return (double) Math.max(maxX, maxY);
            }
        } else if (maxX > minY) {
            high = partitionX - 1;
        } else {
            low = partitionX + 1;
        }
    }
    throw new IllegalArgumentException("Input arrays are not sorted.");
}

猜你喜欢

转载自blog.csdn.net/s_sos0/article/details/132913143