力扣【4】寻找两个正序数组的中位数

题目:

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

进阶:你能设计一个时间复杂度为 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

题解:

import java.util.*;
//大小堆
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //边界条件
        if (nums1 == null && nums2 == null) {
            return 0;
        }
        //将两个数组合并成一个数组
        int[] nums = new int[nums1.length + nums2.length];
        for (int i = 0; i < nums1.length; i++) {
            nums[i] = nums1[i];
        }
        for (int j = 0; j < nums2.length; j++) {
            nums[nums1.length + j] = nums2[j];
        }

        //初始化
        Queue<Integer> left = new PriorityQueue<>((o1,o2) -> (o2 - o1));//大顶堆
        Queue<Integer> right = new PriorityQueue<>((o1,o2) -> (o1 - o2));//小顶堆

        int N = 0;
        for (int i = 0; i < nums.length; i++) {
            if (N % 2 == 0) {
                left.add(nums[i]);
                right.add(left.poll());
            } else {
                right.add(nums[i]);
                left.add(right.poll());
            }
            N++;
        }

        if (N % 2 == 0) {
            return (left.peek() + right.peek())/2.0;
        } else {
            return (double)right.peek();
        }
    }
}
public class Main {
    public static void main(String[] args) {
        int[] nums1 = {1,3};
        int[] nums2 = {2,4};
        Solution solution = new Solution();
        double res = solution.findMedianSortedArrays(nums1, nums2);
        System.out.println("结果:" + res);
    }
}

猜你喜欢

转载自blog.csdn.net/qq1922631820/article/details/113882535