思路一:
归并过程然后取中值。这是一个思路,比较费时间。
import java.util.*; public class Solution { /** * find median in two sorted array * @param arr1 int整型一维数组 the array1 * @param arr2 int整型一维数组 the array2 * @return int整型 */ public int findMedianinTwoSortedAray (int[] arr1, int[] arr2) { // write code here int[] D=merge(arr1,arr1.length,arr2,arr2.length); //D的长度一定是偶数 题目给出 return D[D.length/2-1];//所以这里一定要减去1 可以使用一个测试用例来参考 } public int[] merge(int A[], int m, int B[], int n) { int[] help=new int[m+n]; int p1=0,p2=0,i=0; while(p1<m&&p2<n){ help[i++]=A[p1]<B[p2]?A[p1++]:B[p2++]; } while(p1<m){ help[i++]=A[p1++]; } while(p2<n){ help[i++]=B[p2++]; } return help; } }思路二:
在两个数组中分别取最小值,直到第n个结束就是中值。
import java.util.*; public class Solution { /** * find median in two sorted array * @param arr1 int整型一维数组 the array1 * @param arr2 int整型一维数组 the array2 * @return int整型 */ public int findMedianinTwoSortedAray (int[] arr1, int[] arr2) { // write code here // 从两个数组不断找较小者,找到第n个就返回。 int l = 0, r = 0; int res = 0; while(l + r < arr1.length){ if(arr2[r] < arr1[l]) res = arr2[r++]; else res = arr1[l++]; } return res; } }