【每日一题】leetcode4寻找两个正序数组的中位数

题目描述

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

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

示例

输入:nums1 = [1,3], nums2 = [2]

输出:2.00000

解释:合并数组 = [1,2,3] ,中位数 2

题目分析

leetcode上标注的是一个困难题,但是做起来感觉应该是一个简单题。题目中需要找到两个数组的中位数。首先,如果数据的个数为双数,则中位数是处于中间的两个数的平均值,否则就是中间那个数。然后,两个数组都是有序的,我们只需要将两个数组按顺序遍历一遍,找到中位数即可

解法1

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    int size = nums1.length + nums2.length;
    int start = size % 2 == 0 ? size / 2 + 1 : size / 2 + 2;
    int i = 0 , j = 0;
    int index = 0;
    int current = 0;
    int last = 0;
    while (i < nums1.length && j < nums2.length && index < start) {
        ++ index;
        last = current;
        if (nums1[i] < nums2[j]) {
            current = nums1[i];
            ++ i;
        } else {
            current = nums2[j];
            ++j;
        }
    }
    while (i < nums1.length && index < start) {
        ++ index;
        last = current;
        current = nums1[i];
        ++ i;
    }
    while (j < nums2.length && index < start) {
        ++ index;
        last = current;
        current = nums2[j];
        ++ j;
    }
    if (index == start) {
        if (size % 2 == 0) {
           return (double) (last + current) / 2;
        }
        return last;
    }
    return current;
}

 

posted @ 2022-01-21 09:39  Carol淋  阅读(34)  评论(0编辑  收藏  举报