Question:
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
有两个已经排序好的数组nums1和nums2,大小分别为m和n。查找两个排序数组的中位数。程序运行时复杂度应该是O(log(m n))。
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Answer:
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length = nums1.length + nums2.length;
int array[] = new int[length];
int i,j;
for(i=0;i<nums1.length;i++){
array[i] = nums1[i];
}
for(j=0;j<nums2.length;i++,j++){
array[i] = nums2[j];
}
Arrays.sort(array);
// for(int x=0; x<length; x++){
// System.out.print(array[x]+" ");
// }
if(length%2 != 0){
return (double)array[(length+1)/2-1];
}
else {
double ans = (double)((array[length/2]+array[(length/2)-1])/2.0);
return ans;
}
}
}