LeetCode题解(Golang实现)--Median of Two Sorted Arrays

LeetCode题解(Golang实现)--Median of Two Sorted Arrays,第1张

概述题目 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] 题目

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

以上是内存溢出为你收集整理的LeetCode题解(Golang实现)--Median of Two Sorted Arrays全部内容,希望文章能够帮你解决LeetCode题解(Golang实现)--Median of Two Sorted Arrays所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1275522.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存