Leetcode: Median of Two Sorted Arrays
生活随笔
收集整理的這篇文章主要介紹了
Leetcode: Median of Two Sorted Arrays
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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)).
?
?
2017/2/5更新:如果一定要每次扔一半,使得時間復(fù)雜度為O(log(m+n))。可以在第一個數(shù)組找前k1個,第二個數(shù)組找前k2個,使得k1+k2 == k, 分情況:
1. if A[k1] < B[k2], then A[k1]及之前的、B[k2+1]及之后的都不可能成為第k個元素,所以扔掉
2. else if A[k1] > B[k2], then A[k1+1]及之后的、 B[k2]及之前的都不可能成為第k個元素。扔掉?
if (aMid < bMid) Keep [aRight + bLeft] else Keep [bRight + aLeft] 1 public class Solution { 2 public double findMedianSortedArrays(int A[], int B[]) { 3 if((A.length+B.length)%2==1) 4 return helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1); 5 else 6 return (helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2) 7 +helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1))/2.0; 8 } 9 10 private int helper(int A[], int B[], int i, int i2, int j, int j2, int k) 11 { 12 int m = i2-i+1; 13 int n = j2-j+1; 14 if(m>n) 15 return helper(B,A,j,j2,i,i2,k); 16 if(m==0) 17 return B[j+k-1]; //這是相對距離,不是相對于0,而是這輪起點j,所以決定了25行27行要減posA或posB 18 if(k==1) 19 return Math.min(A[i],B[j]); 20 int posA = Math.min(k/2,m); 21 int posB = Math.min(k-posA, n); 22 23 if(A[i+posA-1]<B[j+posB-1]) 24 return helper(A,B,i+posA,i2,j,j+posB-1,k-posA); 25 else 26 return helper(A,B,i,i+posA-1,j+posB,j2,k-posB); 27 } 28 }?
轉(zhuǎn)載于:https://www.cnblogs.com/EdwardLiu/p/3982815.html
總結(jié)
以上是生活随笔為你收集整理的Leetcode: Median of Two Sorted Arrays的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 域模型向左走(充血),向右走(贫血)
- 下一篇: Whois查询接口文档