funcfindNumInArray(x int, arr []int) (idx int) { l, r := 0, len(arr) for r-l > 0 { mid := int(uint(r+l) >> 1) if arr[mid] < x { l = mid + 1 } else { r = mid } } return l } funcfindMedianOfArray(nums []int)float64 { iflen(nums)%2 == 1 { returnfloat64(nums[len(nums)/2]) } returnfloat64(nums[len(nums)/2]+nums[len(nums)/2-1]) / 2 } funcfindMedianSortedArrays(nums1 []int, nums2 []int)float64 { len1, len2 := len(nums1), len(nums2) if len1 == 0 { return findMedianOfArray(nums2) } if len2 == 0 { return findMedianOfArray(nums1) } totalLength := len1 + len2 var oddLength = totalLength&1 == 1 halfLength := totalLength / 2 l := 0 r := len1 i := 0 numbersInLeft := 0 for r-l > 0 { mid := (l + r) >> 1 n := nums1[mid] i = findNumInArray(n, nums2) numbersInLeft = mid + i if numbersInLeft < halfLength { l = mid + 1 } else { r = mid } } if l >= len1 { if oddLength { returnfloat64(nums2[halfLength-len1]) } else { var a, b int if halfLength-len1-1 < 0 { a, b = nums1[len1-1], nums1[len1-1] } else { a, b = nums2[halfLength-len1-1], nums1[len1-1] } if a < b { a, b = b, a } returnfloat64(nums2[halfLength-len1]+a) / 2 } } i = findNumInArray(nums1[l], nums2) numbersInLeft = l + i if numbersInLeft == halfLength { if oddLength { returnfloat64(nums1[l]) } a, b := -1_000_000_0, -1_000_000_0 if l > 0 { a = nums1[l-1] } if i > 0 { b = nums2[i-1] } if a < b { a, b = b, a } if a == -1_000_000_0 { a = nums2[i] } return (float64(a) + float64(nums1[l])) / 2 } else { return findMedianSortedArrays(nums2, nums1) } }