题目描述
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
思路
先合并排序,后找中位数,复杂度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
}
转载于:https://www.jianshu.com/p/35e6d4f5a627