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

mac2025-01-21  41

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)