4. median-of-two-sorted-arrays, golang

code:

func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
	/*from question : You may assume nums1 and nums2 cannot be both empty.
	*/
	/*assume nums1 and nums2 are both in order
	*/
	
	//ensure that len(nums1) is always smaller than len(nums2)
    len_1, len_2 := len(nums1), len(nums2)
    if len_1 > len_2 {
        nums1, len_1, nums2, len_2 = nums2, len_2, nums1, len_1
    }
    
	//fmt.Printf("nums1:%v, len:%d, cap:%d\n", nums1, nLen_1, cap(nums1))
	//fmt.Printf("nums2:%v, len:%d, cap:%d\n", nums2, nLen_2, cap(nums2))
    //return 0;
    
    nLow, nHigh := 0, len_1;
    nLen    := len_1 + len_2
    nMiddle := (nLen + 1) / 2
    nNums1  := len_1 / 2
    nNums2  := nMiddle - nNums1
    
	//get the nNums1 that separate sum of nums1 and nums2 to left part and right part
    //the length of left part is equal to the length of right part
    //or the length of left part is 1 more than the length of right part
    for {
        if nNums1 > 0 && nums1[nNums1 - 1] > nums2[nNums2] {
            nNums1--
            nHigh = nNums1
            nNums1 = (nHigh + nLow) / 2
            nNums2  = nMiddle - nNums1
        } else if nNums1 < len_1 && nums1[nNums1] < nums2[nNums2 - 1] {
            nNums1++
            nLow = nNums1
            nNums1 = (nHigh + nLow) / 2
            nNums2  = nMiddle - nNums1
        } else {
            //fmt.Printf("nNums1:%d, nNums2:%d\n", nNums1, nNums2)
            //return 0
            
            //get Max value of left part
            nLeftMax := 0
            if 0 == nNums1 {
                nLeftMax = nums2[nNums2 - 1]
            } else if  0 == nNums2 {
                nLeftMax = nums1[nNums1 - 1]
            } else {
                nLeftMax = int(math.Max(float64(nums1[nNums1 - 1]), float64(nums2[nNums2 - 1])))
            }
            if 1 == nLen % 2 {
                return float64(nLeftMax) 
            }
            
            //get Min Value of right part
            nRightMin := 0
            if len_1 == nNums1 {
                nRightMin = nums2[nNums2]
            } else if len_2 == nNums2 {
                nRightMin = nums1[nNums1]
            } else {
                nRightMin = int(math.Min(float64(nums1[nNums1]), float64(nums2[nNums2])))
            }
            
            //fmt.Printf("nLeftMax:%d, nRightMin:%d\n", nLeftMax, nRightMin)
            return float64(nLeftMax + nRightMin) / 2
        }
    }
    
    return 0.0
}

result:
在这里插入图片描述
personal opinion:
buliding mathematical model is always a good way to solve specific problems

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值