Leetcode-Median of Two Sorted Arrays

本文介绍了一种在O(log(m+n))的时间复杂度内找到两个已排序数组A和B中位数的方法。通过调整两个数组的相对位置并比较关键元素来逐步缩小搜索范围。

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 }

 

转载于:https://www.cnblogs.com/lishiblog/p/4166251.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值