leetcode 4 golang Median of Two Sorted Arrays

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值