zoukankan      html  css  js  c++  java
  • Median of Two Sorted Arrays 分类: Leetcode(线性表) 2015-02-04 09:05 54人阅读 评论(0) 收藏

    Median of Two Sorted Arrays

     

    There are two sorted arrays A and B 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)).


    这道题又是一道需要仔细想的题,一开始最容易想的是直接排好序后取第k(k=(m+n)/2)大的值就行了, 不过这样无法满足题目要求的复杂度。还是另一种算法给力,有种二分法的味道。为了方便理解

    对于A,B数组,我们直接比较A[k/2-1]和B[k/2-1],这样就有三种情况

    1.A[k/2-1] < B[k/2-1] , 这说明第k个值一定不在A数组的前k/2个元素中,为什么呢,因为假设我们合并了A,B数组并排好序组成数组C,那么前k/2-1个A中的元素一定在C的0到k中。因为C的k个元素全部由A和B组成,而A[k/2-1] < B[k/2-1],所以A[k/2-1]最前出现在C[k/2-1]最后出现在C[k-2],这说明第k个元素肯定不在A数组的前k/2个元素中。我们也可以用反证法证明,假设A[k/2-1]是第k大的值,但是A中小于k的元素个数至多2/k-1 + B中小于k的元素个数至多k/2 -1 = k-2 显然 A[k/2-1]至多只能是第k-1大的值,矛盾。

    2.A[k/2-1] > B[k/2-1],与1类似同理

    3.A[k/2-1] = B[k/2-1] 此时两个值相等,k/2-1就是我们要的值 


    还需要考虑的一些特殊情况:

    1.m > n

    2.m == 0

    3.k == 1

    4.k/2 > m


    class Solution {
    public:
        double findMedianSortedArrays(int A[], int m, int B[], int n) {
            int total = m + n;
            if (total & 0x1)
                return find_kth(A,m,B,n,total/2+1);
            else
                return (find_kth(A, m, B, n, total / 2) + find_kth(A, m, B, n, total / 2 +1)) / 2.0;
        }
    
    private:
        static int find_kth(int A[], int m, int B[], int n, int k){
            if(m > n) return find_kth(B, n, A, m, k);
            if(m == 0) return B[k-1];
            if(k == 1) return min(A[0], B[0]);
            
            int pa = min(k/2, m);
            int pb = k - pa;
            if(A[pa-1] < B[pb-1])
                return find_kth(A+pa, m - pa, B, n, k-pa);
            else if(A[pa-1] > B[pb-1])
                return find_kth(A, m , B+pb, n-pb, k-pb);
            else
                return A[pa-1];
        } 
    };





    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    spring boot 中@Mapper和@Repository的区别
    yarn和npm的对比以及yarn的使用
    vue环境搭建
    小白的springboot之路(六)、跨域解决方案CORS
    DWR3.0框架入门(1) —— 实现ajax
    DWR3.0框架入门(3) —— ScriptSession的维护及优化
    DWR3.0框架入门(2) —— DWR的服务器推送
    Freemarker入门案例
    dom4j生成和解析xml文件
    struts2拦截器-自定义拦截器,放行某些方法(web.xml配置)
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656960.html
Copyright © 2011-2022 走看看