LeetCode: Median of Two Sorted Arrays

纵然是瞬间 提交于 2020-03-27 17:10:32

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];
    	}
    }
};

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!