• LeetCode 4. 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
    这个问题可以用求两个已排好序的数组中第k大数字来解决
    求在两个已排好序的数组中的第k个数可以参考http://www.cnblogs.com/buptLizer/archive/2012/03/31/2427579.html

    c++代码
     1 class Solution {
     2 public:
     3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
     4         int m = nums1.size();
     5         int n = nums2.size();
     6         int total = m + n;
     7         if(total & 1)
     8             return findKth(nums1, 0, nums2, 0, total / 2 + 1) * 1.0;
     9         else
    10             return (findKth(nums1, 0, nums2, 0, total / 2) + findKth(nums1, 0, nums2, 0, total / 2 + 1)) / 2.0;
    11     }
    12 private:
    13     int findKth(vector<int> &nums1, int i, vector<int> &nums2, int j, int k)
    14     {
    15         if(nums1.size() - i > nums2.size() - j)
    16             return findKth(nums2, j, nums1, i, k);
    17         if(nums1.size() == i)
    18             return nums2[j + k - 1];
    19         if(k == 1)
    20             return min(nums1[i], nums2[j]);
    21         int pa = min(i + k / 2, (int)nums1.size());
    22         int pb = j + k - pa + i;
    23         if(nums1[pa - 1] < nums2[pb - 1])
    24             return findKth(nums1, pa, nums2, j, k - pa + i);
    25         else if(nums1[pa - 1] > nums2[pb - 1])
    26             return findKth(nums1, i, nums2, pb, k - pb + j);
    27         else return nums2[pb - 1];
    28     }
    29 };
  • 相关阅读:
    Python 之解析配置文件模块ConfigParser
    SonarQube代码质量管理平台
    SVN代码统计工具StatSVN
    python 3接口测试
    python+selenium使用chrome时,报错ignore certificate errors
    python3发送邮件(有附件)
    日记
    杂记 包含 serialize().ajaxStart() .ajaxStop()以及其他
    还是要说一下XML。全当日记
    桑心!XML
  • 原文地址:https://www.cnblogs.com/xjtuchenpeng/p/7726471.html
Copyright © 2020-2023  润新知