Leetcode-Median of Two Sorted Arrays

LiBlog發表於2014-12-16

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 }

 

相關文章