LeetCode:4. 寻找两个正序数组的中位数

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

  • 1)题目
  • 2)思路
  • 3)代码
  • 4)结果

1)题目

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

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

示例 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

提示:

  • nums1.length == m
  • nums2.length == n
  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • 1 <= m + n <= 2000
  • -106 <= nums1[i], nums2[i] <= 106

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2)思路

如果有一个数组为空,直接计算另一个数组的中位数,
否则合并成新数组再进行计算。

3)代码

public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
    if (nums1.length == 0) return countMedian(nums2);
    if (nums2.length == 0) return countMedian(nums1);

    // 合并两个数组
    int nums[] = new int[nums1.length + nums2.length];
    int index1 = 0;
    int index2 = 0;
    for (int i = 0;i < nums.length && (index1 < nums1.length || index2 < nums2.length);i++) {
        if (index1 == nums1.length) {
            nums[i] = nums2[index2++];
            continue;
        }
        if (index2 == nums2.length) {
            nums[i] = nums1[index1++];
            continue;
        }
        nums[i] =  (nums1[index1] <= nums2[index2]) ? nums1[index1++]:nums2[index2++];
    }
    return countMedian(nums);
}

// 计算中位数
public static double countMedian(int nums[]){
    if (nums.length == 0) return 0;
    if (nums.length == 1) return nums[0]/1.0;
    int index = nums.length / 2;
    if (nums.length % 2 == 0) {
        return (nums[index - 1] + nums[index])/2.0;
    }
    return nums[index]/1.0;
}

4)结果

LeetCode:4. 寻找两个正序数组的中位数_第1张图片

你可能感兴趣的:(LeetCode,leetcode,算法,数据结构)