You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

69 lines
1.6 KiB

package main
import (
"log"
"sort"
)
/*
* 4. 寻找两个正序数组的中位数
* 给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
*
* 示例 1:
* 输入:nums1 = [1,3], nums2 = [2]
* 输出:2.00000
* 解释:合并数组 = [1,2,3] ,中位数 2
*
* 示例 2:
* 输入:nums1 = [1,2], nums2 = [3,4]
* 输出:2.50000
* 解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
*
* 示例 3:
* 输入:nums1 = [0,0], nums2 = [0,0]
* 输出:0.00000
*
* 示例 4:
* 输入:nums1 = [], nums2 = [1]
* 输出:1.00000
*
* 示例 5:
* 输入:nums1 = [2], nums2 = []
* 输出:2.00000
*
*
* 提示:
* nums1.length == m
* nums2.length == n
* 0 <= m <= 1000
* 0 <= n <= 1000
* 1 <= m + n <= 2000
* -106 <= nums1[i], nums2[i] <= 106
*
*/
func main() {
nums1a, nums2a := []int{1, 3}, []int{2}
nums1b, nums2b := []int{1, 2}, []int{3, 4}
nums1c, nums2c := []int{0, 0}, []int{0, 0}
nums1d, nums2d := []int{}, []int{1}
nums1e, nums2e := []int{2}, []int{}
log.Println(findMedianSortedArrays(nums1a, nums2a))
log.Println(findMedianSortedArrays(nums1b, nums2b))
log.Println(findMedianSortedArrays(nums1c, nums2c))
log.Println(findMedianSortedArrays(nums1d, nums2d))
log.Println(findMedianSortedArrays(nums1e, nums2e))
}
func findMedianSortedArrays(nums1, nums2 []int) float64 {
retLen := len(nums1) + len(nums2)
nums1 = append(nums1, nums2...)
sort.Ints(nums1)
length := retLen / 2
if retLen%2 == 0 {
return float64(nums1[length-1]+nums1[length]) / 2.0
} else {
return float64(nums1[length])
}
}