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

    Solution:

     1 public class Solution {
     2     public double findMedianSortedArrays(int A[], int B[]) {
     3         if (A.length<B.length) findMedianSortedArrays(B,A);
     4 
     5         int lenA = A.length;
     6         int lenB = B.length;
     7         int min=0,max=lenA;
     8         int i=-1,j=-1;
     9         while (min<=max){
    10             i = (max+min)/2;
    11             j = (lenA+lenB)/2-i;
    12             if (j<0)
    13                 max = i-1;
    14             else if (j>lenB)
    15                 min = i+1;
    16             else if (i<lenA && j>0 && A[i]<B[j-1]) 
    17                 min = i+1;
    18             else if (i>0 && j<lenB && A[i-1]>B[j])
    19                 max = i-1;
    20             else break;
    21         }
    22 
    23         int num1 = Integer.MAX_VALUE;
    24         if (i>=0 && i<lenA) num1 = Math.min(num1,A[i]);
    25         if (j>=0 && j<lenB) num1 = Math.min(num1,B[j]);
    26 
    27         if ((lenA+lenB)%2==1) return num1;
    28 
    29         int num2 = Integer.MIN_VALUE;
    30         if (i-1>=0 && i-1<lenA) num2 = Math.max(num2,A[i-1]);
    31         if (j-1>=0 && j-1<lenB) num2 = Math.max(num2,B[j-1]);
    32   
    33         double res = (double)(num1+num2)/2;
    34 
    35         return res;        
    36     
    37         
    38     }
    39 }
  • 相关阅读:
    web框架学习
    css上
    数据库
    线程
    反射以及部分内置方法
    排序函数sort() 和sorted() 之介绍
    类的绑定方法
    继承
    面向对象和类
    混淆矩阵、准确率、召回率
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4166251.html
Copyright © 2011-2022 走看看