You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1001 B

package medianofarrays
import (
"math"
"sort"
)
func median(xs []int) float64 {
half := float64(len(xs)) / 2
if len(xs)%2 == 0 {
return float64(xs[int(half)]+xs[int(half-1)]) / 2
}
return float64(xs[int(half)])
}
func sever(xs []int) (head int, tail []int) {
if len(xs) > 0 {
return xs[0], xs[1:]
}
return math.MaxInt, xs
}
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
if len(nums1) == 0 && len(nums2) == 0 {
return math.NaN()
}
combined := make([]int, len(nums1)+len(nums2))
for i := range combined {
lhead, ltail := sever(nums1)
rhead, rtail := sever(nums2)
if lhead < rhead {
combined[i] = lhead
nums1 = ltail
} else {
combined[i] = rhead
nums2 = rtail
}
}
return median(combined)
}
func FindMedianSortedArrays(nums1 []int, nums2 []int) float64 {
return findMedianSortedArrays(nums1, nums2)
}
func Lazy(nums1 []int, nums2 []int) float64 {
combined := append(nums1, nums2...)
sort.Ints(combined)
return median(combined)
}