Description
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)).
Example
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
My Solution
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int []newArr=new int[nums1.length+nums2.length];
int i=0;
int j=0;
int count=0;
double result;
while(i<nums1.length && j< nums2.length){
while( i<nums1.length && j<nums2.length && nums1[i]<nums2[j]){
newArr[count++]=nums1[i++];
}
while(i<nums1.length && j<nums2.length&&nums1[i]>nums2[j]){
newArr[count++]=nums2[j++];
}
while(i<nums1.length && j<nums2.length&&nums1[i]==nums2[j] ){
newArr[count++]=nums1[i++];
newArr[count++]=nums2[j++];
}
}
while(i<nums1.length){
newArr[count++]=nums1[i++];
}
while(j<nums2.length){
newArr[count++]=nums2[j++];
}
if(0==count%2){
result=(newArr[count/2]+newArr[(count/2)-1])/2.0;
}
else result=newArr[(count/2)];
return result;
}
}
解题思路:将两个数组合并成一个数组,直接求出中位数并返回。
突然想到一个更好的解题方法,可以直接记下中间的那一个或者那两个数,没有必要把循环走完。