LeetCode题解(Golang实现)--Median of Two Sorted Arrays
发布时间:2020-12-16 18:06:43 所属栏目:大数据 来源:网络整理
导读:题目 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 should be O(log (m+n)). Example 1: nums1 = [1,3] nums2 = [2] The median is 2.0 Example
题目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 should be O(log (m+n)). Example 1: nums1 = [1,3]
nums2 = [2]
The median is 2.0
Example 2: nums1 = [1,2]
nums2 = [3,4]
The median is (2 + 3)/2 = 2.5
解题思路最简单的就是将两个数组合并成一个,然后根据中位数的概念计算中位数,当长度n为奇数时,中位数为x((n+1)/2),当长度n为偶数是,中位数为x((n/2)+x(n/2+1))/2 答案func findMedianSortedArrays(nums1 []int,nums2 []int) float64 {
i,j := 0, 0
nums3 := []int{}
for i < len(nums1) && j < len(nums2) {
if nums1[i] < nums2[j] {
nums3 = append(nums3,nums1[i])
i = i + 1
} else {
nums3 = append(nums3,nums2[j])
j = j + 1
}
}
if i < len(nums1) {
for ; i < len(nums1); i++ {
nums3 = append(nums3,nums1[i])
}
}
if j < len(nums2) {
for ; j < len(nums2); j++ {
nums3 = append(nums3,nums2[j])
}
}
lenSums3 := len(nums3)
if lenSums3%2 == 0 {
return (float64(nums3[lenSums3/2-1]) + float64(nums3[lenSums3/2])) / 2.0
} else {
return float64(nums3[(lenSums3+1)/2-1])
}
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |