美文网首页
go语言解leetcode习题 4. Median of Two

go语言解leetcode习题 4. Median of Two

作者: 倒数第三 | 来源:发表于2017-06-13 11:37 被阅读0次

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])
}

相关文章

网友评论

      本文标题:go语言解leetcode习题 4. Median of Two

      本文链接:https://www.haomeiwen.com/subject/ttddqxtx.html