1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import "container/heap"
type Item struct {
val, arrIdx, elemIdx int
}
type MinHeap []Item
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].val < h[j].val }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) { *h = append(*h, x.(Item)) }
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
func FindMedian(arrays [][]int) float64 {
n := 0
for _, arr := range arrays { n += len(arr) }
h := &MinHeap{}
heap.Init(h)
for i, arr := range arrays {
if len(arr) > 0 {
heap.Push(h, Item{arr[0], i, 0})
}
}
count, m1, m2 := 0, 0, 0
mid1, mid2 := (n-1)/2, n/2
for h.Len() > 0 {
item := heap.Pop(h).(Item)
if count == mid1 { m1 = item.val }
if count == mid2 { m2 = item.val }
if count++; count > mid2 { break }
if item.elemIdx+1 < len(arrays[item.arrIdx]) {
heap.Push(h, Item{arrays[item.arrIdx][item.elemIdx+1], item.arrIdx, item.elemIdx+1})
}
}
if n%2 == 0 {
return float64(m1+m2) / 2.0
}
return float64(m2)
}
|