LeetCode: Median of Two Sorted Arrays

Posted 月下之风

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode: Median of Two Sorted Arrays相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/median-of-two-sorted-arrays/solution/

http://www.cnblogs.com/yuzhangcmu/p/4138184.html

http://blog.csdn.net/gao1440156051/article/details/51725845

http://blog.csdn.net/linhuanmars/article/details/19905515

 

class Solution {
public:
	
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
    	int size = m + n;
    	if (size & 0x1){
    		return findKth(A,m,B,n,size/2+1);
    	}else{
    		double a = findKth(A,m,B,n,size/2);
    		double b = findKth(A,m,B,n,size/2+1);
    		//cout<<a<<" "<<b<<endl;
    		return (a + b)/2;
    	}
    	//return mergeSort(A,m,B,n);
    }

    double findKth(int A[], int m, int B[],int n, int k){
    	if (m > n){
    		return findKth(B,n,A,m,k);
    	}
    	if (0 == m){
    		return B[k-1];
    	}
    	if (1 == k){
    		return min(A[0],B[0]);
    	}
    	int pa = min(m,k/2);
    	int pb = k - pa;
    	if (A[pa-1] < B[pb-1]){
    		return findKth(A+pa, m-pa,B,n,k-pa);
    	}else if (A[pa-1] > B[pb-1]){
    		return findKth(A,m,B+pb,n-pb,k-pb);
    	}else{
    		return A[pa-1];
    	}
    }
};

  

以上是关于LeetCode: Median of Two Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode--Median of Two Sorted Arrays

leetcode 4. Median of Two Sorted Arrays (java)

[Leetcode] Median of Two Sorted Arrays

LeetCode--median-of-two-sorted-arrays

#Leetcode# 4. Median of Two Sorted Arrays

LeetCode: Median of Two Sorted Arrays