Title Description
Given two ordered arrays of size and nums1 m and n nums2.
Please find both the median and orderly array, and requires time complexity of the algorithm is O (log (m + n) ).
You can not assume nums1 and nums2 both empty.
Examples
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
Thinking
First merge sort, to find the median, the complexity O ((m + n) log (m + n)).
Code
// Golang
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
nums := append(nums1, nums2...)
sort.Ints(nums)
l := len(nums)
var res float64
if l % 2 != 0 {
res = float64(nums[l/2])
} else {
res = float64(nums[l/2] + nums[l/2 - 1]) / 2
}
return res
}
Reproduced in: https: //www.jianshu.com/p/35e6d4f5a627