码迷,mamicode.com
首页 > 其他好文 > 详细

4. Median of Two Sorted Arrays

时间:2019-02-06 13:16:54      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:EDA   res   ted   example   讲解   and   lse   val   div   

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)).

You may assume nums1 and nums2 cannot be both empty.

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
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
      
        int m = nums1.length, n = nums2.length, left = (m + n + 1) / 2, right = (m + n + 2) / 2;
        return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;
    }
    int findKth(int[] nums1, int i, int[] nums2, int j, int k) {
        if (i >= nums1.length) return nums2[j + k - 1];
        if (j >= nums2.length) return nums1[i + k - 1];
        if (k == 1) return Math.min(nums1[i], nums2[j]);
        int midVal1 = (i + k / 2 - 1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE;
        int midVal2 = (j + k / 2 - 1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE;
        if (midVal1 < midVal2) {
            return findKth(nums1, i + k / 2, nums2, j, k - k / 2);
        } else {
            return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
        }
    }
}

hard名不虚传,是真的hard。不过思想可以看懂,代码实现还是有点困难才能理解,记下来先。

https://leetcode.windliang.cc/leetCode-4-Median-of-Two-Sorted-Arrays.html

http://www.cnblogs.com/grandyang/p/4465932.html

两位大佬的讲解,之后细细品尝

4. Median of Two Sorted Arrays

标签:EDA   res   ted   example   讲解   and   lse   val   div   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10353632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!