4. Median of Two Sorted Arrays

    xiaoxiao2021-03-25  101

    There are two sorted arrays nums1 and nums2 of size m and n respectively.

    Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

    Example 1:

    nums1 = [1, 3] nums2 = [2] The median is 2.0

    Example 2:

    nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5

    寻找两个有序数组的中位数

    public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int i=0,j=0,k = 0; int a=0,b=0; while (k <= (m+n)/2) { if (i < m && j < n) { a = b; b = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++]; } else if (i < m) { a = b; b = nums1[i++]; } else if (j < n) { a = b; b = nums2[j++]; } k++; } if ((m+n)%2 == 1) { return (double) b; } else { return ((double)a + (double)b)/2; } } }
    转载请注明原文地址: https://ju.6miu.com/read-19238.html

    最新回复(0)