# 4.Median of Two Sorted Arrays

time: o(m+n)

space: o(m+n)

 public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1=nums1.length;
int len2=nums2.length;
int[] nums=new int[len1+len2];
int i=0,j=0,k=0;
while(i<len1&&j<len2){
if(nums1[i]<nums2[j]){
nums[k++]=nums1[i];
i++;
}else{
nums[k++]=nums2[j];
j++;
}
}
while(i<len1){
nums[k++]=nums1[i++];
}

while(j<len2){
nums[k++]=nums2[j++];
}
if((len1+len2)%2==0)
return (double)(nums[(len1+len2)/2]+nums[(len1+len2)/2-1])/2;
else
return (double)nums[(len1+len2)/2];
}

 public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1=nums1.length;
int len2=nums2.length;

int k=(len1+len2)/2;
if((len1+len2)%2==0){
return (findkth(nums1,0,len1,nums2,0,len2,k)+findkth(nums1,0,len1,nums2,0,len2,(k+1)))/2;
}else
return findkth(nums1,0,len1,nums2,0,len2,k+1);
}
//start1开始下表，m元素表示a数组个数
public double findkth(int[] a,int start1,int m,int[] b,int start2,int n,int k){
if(m>n)//保证第一个数组元素个数要小于第二个数组
return findkth(b,start2,n,a,start1,m,k);
if(m==0)
return b[start2+k-1];
if(k==1)
return a[start1]<b[start2]?a[start1]:b[start2];
int i=m<k/2?m:k/2;
if(a[start1+i-1]<b[start2+k-i-1])
return findkth(a,start1+i,m-i,b,start2,n,k-i);
else if(a[start1+i-1]>b[start2+k-i-1])
return findkth(a,start1,m,b,start2+k-i,n-k+i,i);
else
return a[start1+i-1];

}

#### 《LeetBook》leetcode题解(4): Median of Two Sorted Arrays[H]——两个有序数组中值问题

2016-04-09 21:24:06

#### leetcode之 median of two sorted arrays

2013-09-10 00:15:50

#### 两个有序数组的中位数Median of Two Sorted Arrays（很重要）

2016-06-21 11:11:03

#### LeetCode(40) Median of Two Sorted Arrays (两排序数组中位数)

2015-09-22 21:18:45

#### leetcode04-Median of Two Sorted Arrays-python

2016-03-31 15:11:13

#### Lintcode6 Merge Two Sorted Arrays solution 题解

2017-04-01 18:51:25

#### Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode

2013-12-16 13:52:04

#### LeetCode（4）Median of Two Sorted Arrays

2015-08-22 20:35:01

#### LintCode Merge Sorted Array 合并排序数组

2015-07-14 16:00:41

#### leetcode 4. Median of Two Sorted Arrays O(log(m+n))解法

2016-09-03 20:21:42