- go语言解leetcode习题 4. Median of Two
- 「每日一道算法题」Median of Two Sorted Ar
- [leetcode题解]Median of Two Sorted
- leetcode第4题 求两个数组的中位数
- go语言解leetcode习题 1. Two Sum
- leetcode-4-Median of Two Sorted
- Leetcode4-Median of Two Sorted A
- Swift LeetCode 系列之4: Median of T
- go语言解leetcode习题 2. Add Two Numbe
- LeetCode 4. Median of Two Sorted
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
此题难度为Hard,但是其实挺简单的,题目中要求复杂度为O(log (m+n)),又给了两个排序好的数组,归并排序嘛。
解法如下:
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
result := []int{}
l, r := 0, 0
for l < len(nums1) && r < len(nums2) {
if nums1[l] < nums2[r] {
result = append(result, nums1[l])
l++
} else {
result = append(result, nums2[r])
r++
}
}
result = append(result, nums1[l:]...)
result = append(result, nums2[r:]...)
if len(result)%2 == 0 {
return float64(result[len(result)/2-1]+result[len(result)/2]) / 2
}
return float64(result[len(result)/2])
}
网友评论