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

来源:互联网 发布:java list remove方法 编辑:程序博客网 时间:2024/06/04 20:08

题目

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])    }}
阅读全文
0 0