zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    缺失值的常见填充方法
    多变量线性回归
    回归(补充)
    单变量线性回归
    监督学习和非监督学习
    Java学习-数组(1)
    如何发布一个npm包(基于vue)
    《麦肯锡教给我的写作武器》摘录
    自定义博客样式
    ubuntu 下配置elasticSearch
  • 原文地址:https://www.cnblogs.com/xjtuchenpeng/p/7726471.html
Copyright © 2011-2022 走看看