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)).

     1 public class Solution {
     2     public double findMedianSortedArrays(int A[], int B[]) {
     3         int alen = A.length;
     4         int blen = B.length;
     5         if((alen + blen) % 2 == 1) return findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen + 1) / 2);
     6         else return (double) (findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen) / 2) + findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen + 2) / 2)) / 2.0;
     7     }
     8     private int findKthElement(int arra[], int arrb[], int ast, int and, int bst, int bnd, int num){
     9         if(ast > and) return arrb[bst + num - 1];
    10         if(bst > bnd) return arra[ast + num - 1];
    11         int amid = (ast + and) / 2;
    12         int bmid = (bst + bnd) / 2;
    13         int len = amid - ast + 1 + bmid - bst + 1;
    14         if(arra[amid] < arrb[bmid]){
    15             if(len <= num) return findKthElement(arra, arrb, amid + 1, and, bst, bnd, num - amid + ast - 1);
    16             else return findKthElement(arra, arrb, ast, and, bst, bmid - 1, num);
    17         }else{
    18             if(len <= num) return findKthElement(arra, arrb, ast, and, bmid + 1, bnd, num - bmid + bst - 1);
    19             else return findKthElement(arra, arrb, ast, amid - 1, bst, bnd, num);
    20         }
    21     }
    22 }
  • 相关阅读:
    CSS3中新增的对文本和字体的设置
    PAT1107:Social Clusters
    Git的一些操作
    PAT1029:Median
    PAT1024:Palindromic Number
    PAT1028:List Sorting
    PAT1035: Password
    PAT1133:Splitting A Linked List
    PAT1017:Queueing at Bank
    PAT1105:Spiral Matrix
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3880003.html
Copyright © 2011-2022 走看看