4. 寻找两个有序数组的中位数

题目:

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。

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

示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/

分析:

首先想到的是将数组所有元素放在同一个数组中,然后进行排序,排序之后取中位数就简单了,按照此思路得到以下代码:

class Solution {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] nums = join(nums1,nums2);
        double num = midMethod(nums);
        return num;
    }
    /**
     * 将两个数组元素组合到一个数组中,返回结果有序
     */
    public static int[] join(int a[],int b[]) {
        List<Integer> testList = new ArrayList<Integer>();
        //遍历添加给入数组元素
        for (int j = 0; j < a.length; j++) {
            testList.add(a[j]);
        }
        for (int k = 0; k < b.length; k++) {
            testList.add(b[k]);
        }
        int c[] = new int[testList.size()];
        for (int i = 0; i < alist.size(); i++) {
            c[i] = alist.get(i);
        }
        Arrays.sort(c);
        return c;
    }
    /**
     * 得到中位数
     */
    public static double midMethod(int[] nums) {
        double mid = nums.length / 2.0 ;
        double num = 0;
        if (mid == 0) {
            //若给定的两个数组都为空,不做处理
        } else if (Math.floor(mid) != mid) {
            num = nums[(int)mid];
        } else {
            num = (nums[(int)mid-1] + nums[(int)mid]) / 2.0;
        }
        return num;
    }
}
View Code
原文地址:https://www.cnblogs.com/doona-jazen/p/11422514.html