寻找两个正序数组的中位数 |刷题打卡

212 阅读1分钟

掘金团队号上线,助你 Offer 临门! 点击 查看大厂春招职位

一、题目描述:

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

示例 1:

输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2

示例 2:

输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5

示例 3:

输入:nums1 = [0,0], nums2 = [0,0]
输出:0.00000

示例 4:

输入:nums1 = [], nums2 = [1]
输出:1.00000

示例 5:

输入:nums1 = [2], nums2 = []
输出:2.00000

题目地址:leetcode-cn.com/problems/me…

二、思路分析:

做法是将两个数组进行合并,合并后再遍历一遍,一定要注意,是是合并后的中位数,不是两个数组的中位数。由于已经知道了两个数组的长度,所以中位数的位置是确定的,然后再利用归并排序,归并到一半就能够出结果了。

三、AC 代码:

public class MedianTwoArrays {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int T = nums1.length + nums2.length;
        double result;
        List<Integer> nums3 = new ArrayList<>(T);
        int i1 = 0;
        int i2 = 0;
        int i3 = 0;

        int num1;
        int num2;
        while (i3 <= T / 2) {
            num1 = (i1 == nums1.length) ? Integer.MAX_VALUE : nums1[i1];
            num2 = (i2 == nums2.length) ? Integer.MAX_VALUE : nums2[i2];
            if (num1 < num2) {
                nums3.add(num1);
                i1++;
            } else {
                nums3.add(num2);
                i2++;
            }
            i3++;
        }

        int temp;
        if (T % 2 != 0) {
            temp = nums3.get(i3 - 1);
            result = (temp + temp) / 2.0;
        } else {
            temp = nums3.get(i3 - 2) + nums3.get(i3 - 1);
            result = temp / 2.0;
        }
        return result;
    }
}

四、总结:

归并排序本身并不难,不过细节上需要注意一些边界点,和边界参数。可以注意一下以下几组测试case:

num1 = [],num2 = [1,2,3]
num1 = [1,2,3],num2 = [1]
num1 = [1],num2 = [1,2,3]