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)).
You may assume nums1 and nums2 cannot be both empty.
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
Solution 1:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int totalLength = nums1.length+nums2.length;
int[] helper = new int[totalLength];
int count = 0;
int left = 0;
int right = 0;
while(left<nums1.length && right<nums2.length && count<=((totalLength/2)+1)){
if(nums1[left]<=nums2[right]){
helper[count] = nums1[left];
left++;
}else{
helper[count] = nums2[right];
right++;
}
count++;
}
while(count<=(totalLength/2)+1){
if(left<nums1.length){
helper[count] = nums1[left];
left++;
}else if(right<nums2.length){
helper[count] = nums2[right];
right++;
}
count++;
}
double median;
int mid = totalLength/2;
if(totalLength%2==0) {
//System.out.println(helper[mid-1]+" "+helper[mid]);
median = (double)(helper[mid-1]+helper[mid])/2;
}else{
median = (double)helper[mid];
}
return median;
}
}