Median of Two Sorted Arrays

来源:互联网 发布:adobe for mac 编辑:程序博客网 时间:2024/05/01 10:36

Median of Two Sorted Arrays

 Total Accepted: 44236 Total Submissions: 247850
<p style="margin-top: 0px; margin-bottom: 10px; line-height: 30px; box-sizing: border-box;">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)).</p><p style="margin-top: 0px; margin-bottom: 10px; line-height: 30px; box-sizing: border-box;"></p><div id="tags" class="btn btn-xs btn-warning" style="box-sizing: border-box; display: inline-block; padding: 1px 5px; margin-bottom: 0px; line-height: 1.5; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; -webkit-user-select: none; border: 1px solid rgb(238, 162, 54); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; color: rgb(255, 255, 255); width: 80px; background-image: none; background-color: rgb(240, 173, 78);">Show Tags</div>
class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n) {//check...if(A == NULL && B == NULL || m<0 || n<0)return -1;if(m>0 && n==0)return m_ArrayMedian(A,0,m-1);if(m == 0 && n>0)return m_ArrayMedian(B,0,n-1);int nSum = m+n;//总元素个数int Al = 0,Ar = m-1,Bl = 0,Br = n-1;while(1){if(nSum == 1){if((Ar-Al+1) == 1)return A[Al];elsereturn B[Bl];}else if(nSum == 2){if((Ar-Al+1) == 2)return (double)(A[Al]+A[Ar])/2;else if((Ar-Al+1) == 0)return (double)(B[Bl]+B[Br])/2;elsereturn (double)(A[Al]+B[Bl])/2;}else{//去掉一个最小数if(Al>Ar)return m_ArrayMedian(B,Bl,Br);else if(Bl>Br)return m_ArrayMedian(A,Al,Ar);else{if(A[Al]<B[Bl])Al ++;elseBl ++;}//去掉一个最大数if(Al>Ar)return m_ArrayMedian(B,Bl,--Br);else if(Bl>Br)return m_ArrayMedian(A,Al,--Ar);else{if(A[Ar]>B[Br])Ar --;elseBr --;}}nSum = nSum - 2;}    }double m_ArrayMedian(int A[],int l,int r){int sum = r-l+1;if(sum&1 == 1)return A[(l+r)/2];elsereturn (double)(A[(l+r-1)/2]+A[(l+r+1)/2])/2;}};

My Submissions


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

Show Tags
0 0
原创粉丝点击