Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit e8988f6

Browse filesBrowse files
add solution 0004 [golang]
1 parent 3aa9c9d commit e8988f6
Copy full SHA for e8988f6

File tree

Expand file treeCollapse file tree

1 file changed

+68
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+68
-0
lines changed
Open diff view settings
Collapse file
+68Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* Report by leetcode.com
3+
* Runtime: 16 ms, Memory Usage: 5.4 MB
4+
*/
5+
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
6+
mathMax := func(a, b int) int {
7+
if a > b {
8+
return a
9+
}
10+
return b
11+
}
12+
mathMin := func(a, b int) int {
13+
if a < b {
14+
return a
15+
}
16+
return b
17+
}
18+
19+
var len1, len2 int
20+
len1 = len(nums1)
21+
len2 = len(nums2)
22+
if len1 > len2 {
23+
var tmp []int = nums1
24+
nums1 = nums2
25+
nums2 = tmp
26+
var t int = len1
27+
len1 = len2
28+
len2 = t
29+
}
30+
31+
var min, max int = 0, 0
32+
max = len1
33+
34+
halfLen := (len1 + len2 + 1) / 2
35+
36+
for min <= max {
37+
i := (min + max) / 2
38+
j := halfLen - i
39+
40+
if i < max && nums2[j-1] > nums1[i] {
41+
min++
42+
} else if i > min && nums1[i-1] > nums2[j] {
43+
max--
44+
} else {
45+
var maxLeft int
46+
if i == 0 {
47+
maxLeft = nums2[j-1]
48+
} else if j == 0 {
49+
maxLeft = nums1[i-1]
50+
} else {
51+
maxLeft = mathMax(nums1[i-1], nums2[j-1])
52+
}
53+
if ((len1 + len2) & 1) == 1 {
54+
return float64(maxLeft)
55+
}
56+
var minRight int
57+
if i == len1 {
58+
minRight = nums2[j]
59+
} else if j == len2 {
60+
minRight = nums1[i]
61+
} else {
62+
minRight = mathMin(nums2[j], nums1[i])
63+
}
64+
return float64(maxLeft+minRight) / 2
65+
}
66+
}
67+
return 0
68+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.