Problem
Analysis Process
The problem says there are two arrays and the overall run time complexity should be O(log(m+n)),it’s natural to think about merging arrays and binary search.
By the definition of median, when m+n is odd,the median is the (m+n)/2 element in two ordered arrays.when m+n is even,median is the (m+n)/2 and (m+n)/2+1 element in two ordered arrays
So, this problem translates to looking for the k smallest number in two ordered arrays
Suppose the two ordered arrays are A and B
1.If A[k/2−1]<B[k/2−1],the only numbers that are less than A[k/2−1] are the first k/2−1 of A and the first k/2−1 of B.So,A[k/2−1] can’t be the k element,rule out A[0] to A[k/2−1]
2.If A[k/2−1]>B[k/2−1],rule out B[0] to B[k/2−1]
3.If A[k/2−1]=B[k/2−1],same as the first case
Consider the following special cases
1.f A[k/2−1] or B[k/2−1] cross the line ,pick the last element in the corresponding array
2. If an array is empty, all elements in the array are excluded, and we can simply return the k smallest element in another array
3. If k=1, we just return the minimum value of the first element of both arrays
Code
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
Length := len