1. 程式人生 > >【LeetCode】median of two sorted arrays

【LeetCode】median of two sorted arrays

個數 i++ target 們的 data- 關於 arrays 推斷 get

題目:median of two sorted arrays

知識點:二分查找,中位數定義

public class Solution { 
        /*
 * 關於:leetcode 第二題 給定兩個排好序的數組。找到它們的中位數,要求:時間復雜度o(log(m+n));
 * 變形:找第k個數
 * 方法:1.遍歷。時間復雜度為o(m+n),從頭開始分別遍歷兩數組的數,依照大小計數,直到第k個數
 * 		2.遞歸,由於兩個數組是排好序的。所以先各取第k/2的數比較,小的一邊必定全都在第k個數之前(反證法)
 * 大的一邊則可能不全在k前,於是遞歸再找剩下的k/2個數。
 * 		返回條件:1.一個數組為空時,直接返回還有一個數組第k個數
 * 				2.k=1,返回min(A[0],B[0])
 * 				3.A[k/2-1] == B[k/2-1],返回當中一個的值
 */ 
	public double findMedianSortedArrays(int A[], int B[]) {
		int n = A.length;
		int m = B.length;
		int total = n+m;
		if(total%2 == 1){	//假設兩個數組的個數相加是奇數。不能有total&0x1推斷。。
			return culMedian(A,n,B,m,total/2+1);
		}
		else
			return (culMedian(A,n,B,m,total/2)+culMedian(A,n,B,m,total/2+1))/2.0;
    }
	public double culMedian(int A[],int n,int B[],int m,int k){
		if(n == 0)
			return B[k-1];
		if(m==0)
			return A[k-1];
		if(k == 1)
			return A[0]<B[0]?A[0]:B[0];
		int a = k/2 < n ? k/2 : n;  //註意邊界條件的考慮
		int b = k-a < m ?

k-a : m; if(A[a-1] < B[b-1]){ //java不能直接用A+a傳遞指針。。。還有別的方法嗎??? int iA[] = new int[n-a]; for(int i = a;i < n;i++) iA[i-a] = A[i]; return culMedian(iA,n-a,B,m,k-a); } else if(A[a-1] > B[b-1]){ int iB[] = new int[m-b]; for(int i = b;i < m;i++) iB[i-b] = B[i]; return culMedian(A,n,iB,m-b,k-b); } else return A[a-1]; } }



【LeetCode】median of two sorted arrays