LeetCode-Median of Two Sorted Arrays

本文介绍了一种寻找两个已排序数组中位数的方法。通过使用双指针遍历两个数组,可在O(n)的时间复杂度和O(1)的空间复杂度下找到中位数。文章提供了完整的Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4. 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

思路:
用两个指针*A、*B指向两个数组,因为两个数组已经排序,所以*A、*B指针所对应的数据的排序就是合并后数据的排序,根据两个数组的长度即可确定中位数的位置X。当指针*A、*B移动位置的合为X时,该数就是中位数。
时间复杂度O(n),空间复杂度:O(1).

/**
 * Created by sunny.su on 2017/2/28.
 */
public class MedianOfTwoSortedArrays {
    public static void main(String[] args) {
        int[] nums1 = {};
        int[] nums2 = {2,3};
        System.out.println(findMedianSortedArrays(nums1, nums2));
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        double re = 0;
        int total = nums1.length + nums2.length, x = nums1.length, y = nums2.length;
        if (total == 2) {
            if (x > 0 && y > 0) {
                return (nums1[--x] + nums2[--y]) / 2.0;
            }
            return x > 0 ? (nums1[--x] + nums1[--x]) / 2.0 : (nums2[--y] + nums2[--y]) / 2.0;
        }
        if (total == 1) {
            return x > 0 ? nums1[--x] : nums2[--y];
        }
        while (x + y > Math.ceil(total / 2)) {
            if (x == 0) re = nums2[--y];
            if (y == 0) re = nums1[--x];
            if (x > 0 && y > 0) re = nums1[x - 1] > nums2[y - 1] ? nums1[--x] : nums2[--y];
        }
        if (total % 2 == 0) {
            if (x == 0) re += nums2[--y];
            if (y == 0) re += nums1[--x];
            if (x > 0 && y > 0) re += nums1[x - 1] > nums2[y - 1] ? nums1[--x] : nums2[--y];
            re = re / 2;
        }
        return re;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值