-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (73 loc) · 1.43 KB
/
main.go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"fmt"
"math"
)
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
if len(nums1) > len(nums2) {
return findMedianSortedArrays(nums2, nums1)
}
total := len(nums1) + len(nums2)
half := (total + 1) / 2
var Aleft, Aright float64
var Bleft, Bright float64
low, high := 0, len(nums1)-1
for {
partitionX := (low + high) / 2
partitionY := half - partitionX - 2
if partitionX >= 0 {
Aleft = float64(nums1[partitionX])
} else {
Aleft = math.Inf(-1)
}
if (partitionX + 1) < len(nums1) {
Aright = float64(nums1[partitionX+1])
} else {
Aright = math.Inf(1)
}
if partitionY >= 0 {
Bleft = float64(nums2[partitionY])
} else {
Bleft = math.Inf(-1)
}
if (partitionY + 1) < len(nums2) {
Bright = float64(nums2[partitionY+1])
} else {
Bright = math.Inf(1)
}
fmt.Println(partitionX, partitionY, Aleft, Aright, Bleft, Bright)
// partition is correct
if Aleft <= Bright && Bleft <= Aright {
// odd
if total%2 == 1 {
return max(Aleft, Bleft)
}
// even
return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
} else if Aleft > Bright {
high = partitionX - 1
} else {
low = partitionX + 1
}
}
return 1.0
}
func max(a, b float64) float64 {
if a > b {
return a
}
return b
}
func min(a, b float64) float64 {
if a < b {
return a
}
return b
}
func main() {
r := findMedianSortedArrays(
[]int{},
[]int{1},
)
fmt.Println(r)
}