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

Sign up
Appearance settings

Commit 7e600d7

Browse files
Merge pull request doocs#159 from lightfish-zhang/master
update solution 0004, add golang code, fix bug for java code
2 parents 3aa9c9d + 71e008c commit 7e600d7

File tree

2 files changed

+69
-1
lines changed

2 files changed

+69
-1
lines changed
Lines 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+
}

‎solution/0004.Median of Two Sorted Arrays/Solution.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public double findMedianSortedArrays(int[] nums1, int[] nums2) {
3333
return maxLeft;
3434
}
3535

36-
int minRight = i == len1 ? nums2[j] : j == len2 ? nums1[i] : Math.min(nums2[i], nums1[j]);
36+
int minRight = i == len1 ? nums2[j] : j == len2 ? nums1[i] : Math.min(nums2[j], nums1[i]);
3737

3838
return (maxLeft + minRight) / 2.0;
3939

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /