zoukankan      html  css  js  c++  java
  • leetCode_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)).


         找中间数,要注意当(m+n) 是奇数时,中间数为第(m+n)/2 +1 ,当(m+n)为偶数时,中间数为第(m+n)/2   和(m+n) 两数的平均。所以该题可以转换为在两个排序的数列中,寻找第K个数。

         时间复杂度为O(log (m+n)),考虑使用二分查找,在两个数组中对比A[half]和B[half], 然后裁剪小的一个数组,不断裁剪直到1)小的数组为空,此时输出大的数组的第k个数(注意裁剪数组时,K也会做相应的裁剪); 2)当k== 1 时 ,返回 min(A[0], B[0])

    View Code
    class Solution {
    public:
        double findKthSortedArrays(int A[], int m, int B[], int n,int k){
            
            if(m > n) return findKthSortedArrays(B, n, A, m, k);
            if(0 == m) return B[k-1];
            if(1 == k) return A[0] < B[0] ? A[0] : B[0];
            
            int pa = k>>1 < m ? k>>1: m ;
            int pb = k - pa;
            if(A[pa -1] <= B[pb-1])
                    return findKthSortedArrays(A+pa, m-pa, B, n,k-pa );
                else
                    return findKthSortedArrays(A, m , B+pb, n-pb, k -pb) ;
            
        }
        double findMedianSortedArrays(int A[], int m, int B[], int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(1== (m+n)%2)
                    return findKthSortedArrays(A, m, B, n, (m+n)/2 + 1);
               else
                    return (findKthSortedArrays(A, m, B, n, (m+n)/2 + 1) + findKthSortedArrays(A, m, B, n, (m+n)/2)) /2 ;
               
            
        }
    };
    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    Android EditText 文本框实现搜索和清空效果
    Android学习笔记之打钩显示输入的密码
    Mysql limit offset
    Android SDK更新以及ADT更新出现问题的解决办法
    Android Broadcast Receiver 使用入门
    立即执行函数
    JS 原型 & 继承
    JS 对象
    chrome extension overview
    JS 修改元素
  • 原文地址:https://www.cnblogs.com/graph/p/2986413.html
Copyright © 2011-2022 走看看