zoukankan      html  css  js  c++  java
  • 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大的元素。我们可以如此处理,先比较A和B的第k/2个数大小,每次把小的序列删去k/2个数,保证不会删去第k大数,如果一个序列没有k/2个数,那么就比较第min(m,n)个数的大小,去除一个数组,递归结束。

    class Solution {
    public:
        double findKSortedArrays(int A[],int m,int B[],int n,int k)
        {
            if(m==0)
                return B[k-1];
            else if(n==0)
                return A[k-1];
            if(k==1)
                return min(A[0],B[0]);
            int index=min(m,n);
            int half=k/2;
            index=min(index,half);
            if(A[index-1]<B[index-1])
            {
                return findKSortedArrays(A+index,m-index,B,n,k-index);
            }
            else
                return findKSortedArrays(A,m,B+index,n-index,k-index);
        }
        double findMedianSortedArrays(int A[], int m, int B[], int n) {
            int total=m+n;
            if(total&0x01)
                return findKSortedArrays(A,m,B,n,total/2+1);
            else
                return (findKSortedArrays(A,m,B,n,total/2+1)+findKSortedArrays(A,m,B,n,total/2))/2;
        }
    };
  • 相关阅读:
    java学习笔记
    androd Sdk manager配置
    50ms延时程序
    89c51中断入口地址表
    打印杨辉三角--队列的应用
    栈的应用--括号匹配
    哈夫曼编码---数据压缩
    PS转手绘
    数据结构学习思路
    第三届蓝桥杯省赛---第39级台阶
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3823716.html
Copyright © 2011-2022 走看看