zoukankan      html  css  js  c++  java
  • leetCode之Median of Two Sorted Arrays

    【题目描述】

    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
    

     【解题思路】

    1、整体排序,去中间值,但是,实际上,我们不需要完整的排序完成,只需要排序middle左边的即可,这样就能保证middle所在的位置是中间位置。

    2、需要考虑num1和mun2全部长度为偶数和奇数的问题,因为如果是奇数,中间值为一个,如果是偶数,中间值为两个。这个其实,终归是要在两个数组中查找一个具体的值。

    3、当一个数组已经遍历完了,但没有找到值时,要在另外一个数组中继续遍历。

    【代码实现】

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int n1 = nums1.length;
            int n2 = nums2.length;
            int total = n1 + n2;
            if(total % 2 == 1)//奇数情况
            {
                return findMiddle(nums1, nums2, n1, n2, (total/2 + 1));
            }
            else
            {
                return (findMiddle(nums1, nums2, n1, n2, (total/2)) + findMiddle(nums1, nums2, n1, n2, (total/2 + 1)))/2;
            }
            
        }
    
        private double findMiddle(int[] nums1, int[] nums2, int n1, int n2, int midIndex)
        {
            double middle = 0.0;
            int i = 0, j = 0;
            for(; i<n1 && j<n2; )
            {
                if(nums1[i] < nums2[j])
                {
                    i++;
                    middle = nums1[i-1];
                }
                else
                {
                    j++;
                    middle = nums2[j-1];
                }
                if((i+j)  == midIndex)
                {
                    break;
                   
                }
            }
            while(i<n1 && ((i+j) < midIndex))
            {
                i++;
                middle = nums1[i-1];
                if((i+j)  == midIndex)
                {
                    break;
                }
            }
            while(j<n2 && ((i+j) < midIndex))
            {
                j++;
                middle = nums2[j-1];
                if((i+j)  == midIndex)
                {
                    break;
                }
            }
            return middle;
        }

    【后续】

    发现了更好的方法,通过分治来实现,方法确实巧妙。

    可参考链接:

    https://hk029.gitbooks.io/leetbook/%E5%88%86%E6%B2%BB/004.%20Median%20of%20Two%20Sorted%20Arrays[H]/004.%20Median%20of%20Two%20Sorted%20Arrays[H].html

  • 相关阅读:
    Java中间件:淘宝网系统高性能利器(转)
    淘宝的数据库拆分(TDDL)(转)
    java web几种开发模式(转)
    C++模板【转】
    set[c++]
    C# jsonhelper
    Vector[C++]
    list[C++]
    map[C++]
    C[泊车管理系统]
  • 原文地址:https://www.cnblogs.com/woniu4/p/8425207.html
Copyright © 2011-2022 走看看