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)).
这个题目实际上就是先用快速排序进行合并,然后求中间值。
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int [] num = new int [nums1.length+nums2.length];
int index1=0;
int index2=0;
int index = 0;
while(index1<nums1.length&&index2<nums2.length){
if(nums1[index1]<nums2[index2]){
num[index]=nums1[index1];
index1++;
}
else{
num[index]=nums2[index2];
index2++;
}
index++;
}
while(index1<nums1.length){
num[index++]=nums1[index1++];
}
while(index2<nums2.length){
num[index++]=nums2[index2++];
}
if(index%2!=0){
index = num.length/2;
return num[index];
}
else{
index = num.length/2;
return (num[index]+num[index-1])/(double)2;
}
}
}