leetcode 4 golang Median of Two Sorted Arrays

来源:互联网 发布:如何选基金 知乎 编辑:程序博客网 时间:2024/06/03 17:44

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

两个有序数组的中卫数,可以转换为求第k小的数
奇数是找到第k小的就可以了
偶数是找到k 和 k + 1 在取平均值

func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {    n1 := nums1    n2 := nums2    pa := 0 //第一个数组的指针    pb := 0 //第二个数组的指针    k := 0 //找到的第k小的数    n1len := len(n1)     n2len := len(n2)    first := 0 //存最后找到的数    second := 0 //存最后找到的数    max := (n1len + n2len) / 2 //k到这个值停止    for {        if k > max {            break        }        min := 0        //考虑不一样长的问题        if pa < n1len && pb < n2len{            item_n1 := n1[pa]            item_n2 := n2[pb]            if item_n1 < item_n2 {              min = item_n1              pa ++             k++            }else{                min = item_n2                pb++                k++            }        }else if pa < n1len {            min = n1[pa]            pa ++             k++        }else{            min = n2[pb]            pb++            k++        }        //考虑奇数偶数情况      if (n1len + n2len) % 2 == 0 {            if (k - 1) == (max - 1) {                first = min            }            if (k - 1) == max {                second = min            }        }else{            if (k - 1) == max {                first = min                second = 0            }        }        }    if (n1len + n2len) % 2 == 0{        return (float64(first) + float64(second)) / 2    }else{        return float64(first)        // fmt.Println(first)    }}
0 0