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 shoshould be O (log (m + n ))., respectively
Solution: Combine Two arrays and create a Map object to store the ordered key-value pairs. The key is the serial number and the value is the array value. The median result is discussed in two cases:
1. m + n is an odd number: (m + n)/2 is the median.
2. m + n is an even number (m + n)/2-1) + (m + n)/2)/2 is the median.
Public class FindMedianNum {
Public static void main (String [] args ){
Int [] a = {1, 2, 4, 5, 10 };
Int [] B = {3, 5, 6, 7 };
Double median = findMedianNum (a, B );
System. out. println (median );
}
Public static double findMedianNum (int [] a, int [] B ){
Int m = a. length;
Int n = B. length;
Int I = 0, j = 0, k = 0;
If (m = 1 & n = 0 ){
Return a [0];
}
If (m = 0 & n = 1 ){
Return B [0];
}
Map <Integer, Integer> map = new HashMap <Integer, Integer> ();
While (I <m & j <n ){
If (a [I] <= B [j]) {
Map. put (k, a [I]);
++ I;
++ K;
} Else {
Map. put (k, B [j]);
++ J;
++ K;
}
}
While (I <m ){
Map. put (k, a [I]);
++ I;
++ K;
}
While (j <n ){
Map. put (k, B [j]);
++ J;
++ K;
}
If (m + n) % 2 = 0 ){
Return (double) (map. get (m + n)/2-1) + map. get (m + n)/2)/2;
} Else {
Return (double) map. get (m + n)/2 );
}
}
}