Skip to content

Latest commit

 

History

History
26 lines (22 loc) · 719 Bytes

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

File metadata and controls

26 lines (22 loc) · 719 Bytes

方法一:暴力求解。

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n = nums1.length, m = nums2.length;
        int idx = 0;
        int[] nums = new int[n + m];
        for (int i = 0, j = 0; i < n || j < m; idx++) {
            int num1 = i < n ? nums1[i] : Integer.MAX_VALUE;
            int num2 = j < m ? nums2[j] : Integer.MAX_VALUE;
            if (num1 < num2) {
                nums[idx] = num1;
                i++;
            } else {
                nums[idx] = num2;
                j++;
            }
        }
        return (n + m) % 2 == 0 ? (double)(nums[(n + m) / 2 - 1] + nums[(n + m) / 2]) / 2 : nums[(n + m) / 2];
    }
}