4. 寻找两个正序数组的中位数(leetcode)

题目描述

给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。

请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

示例

nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0

nums1 = [1, 2] nums2 = [3, 4]

则中位数是 (2 + 3)/2 = 2.5

代码

public class 两个正序数组的中位数 {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0) {
            return nums2.length % 2 == 0 ?
                    (nums2[nums2.length / 2] + nums2[(nums2.length / 2) - 1]) / 2.0
                    : nums2[nums2.length / 2] / 1.0;
        }

        if (nums2 == null || nums2.length == 0) {
            return nums1.length % 2 == 0 ?
                    (nums1[nums1.length / 2] + nums1[(nums1.length / 2) - 1]) / 2.0
                    : nums1[nums1.length / 2] / 1.0;
        }
        int[] temp = new int[nums1.length + nums2.length];
        int i = 0;
        int j = 0;
        int k = 0;
        while (true) {
            if (nums1[i] > nums2[j]) {
                temp[k] = nums2[j];
                j++;
                k++;
                if (j >= nums2.length) {
                    for (int z = i; z < nums1.length; z++) {
                        temp[k] = nums1[z];
                        k++;
                    }
                    break;
                }
            } else {
                temp[k] = nums1[i];
                i++;
                k++;
                if (i >= nums1.length) {
                    for (int z = j; z < nums2.length; z++) {
                        temp[k] = nums2[z];
                        k++;
                    }
                    break;
                }
            }
        }

        return temp.length % 2 == 0 ? (temp[temp.length / 2] + temp[(temp.length/2) - 1]) / 2.0
                : temp[temp.length / 2] / 1.0;

    }

    public static void main(String[] args) {
        两个正序数组的中位数 test = new 两个正序数组的中位数();
        int[] nums1 = {};
        int[] nums2 = {1};
        double result = test.findMedianSortedArrays(nums1, nums2);
        System.out.println(result);
    }
}

思路

  1. 易知,如若求单个有序数组的中位数,可大致分两种情况。
    (当数组长度为偶数的时候,中位数是(A[A.length / 2] + A[(A.length / 2) - 1]) )/ 2.0,否则中位数是(A[A.length / 2])
  2. 设置一个长度为数组nums1和nums2长度之和的数组temp,将nums1和nums2合并到temp。(关于两个数组的合并请查看代码)
  3. 根据(1)方法找到中位数,并返回。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值