Skip to content

Commit 1d2b6fd

Browse files
committed
Create 0004-median-of-two-sorted-arrays.swift
1 parent 9993b1c commit 1d2b6fd

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
3+
if nums1.count > nums2.count {
4+
return findMedianSortedArrays(nums2, nums1)
5+
}
6+
7+
var m = nums1.count
8+
var n = nums2.count
9+
var l = 0
10+
var r = m
11+
12+
while l <= r {
13+
var pa = (l + r) / 2
14+
var pb = (m + n + 1) / 2 - pa
15+
16+
var maxLeftA = pa == 0 ? Int.min : nums1[pa - 1]
17+
var minRightA = pa == m ? Int.max : nums1[pa]
18+
var maxLeftB = pb == 0 ? Int.min : nums2[pb - 1]
19+
var minRightB = pb == n ? Int.max : nums2[pb]
20+
21+
if maxLeftA <= minRightB && maxLeftB <= minRightA {
22+
if (m + n) % 2 == 0 {
23+
return Double((max(maxLeftA, maxLeftB) + min(minRightA, minRightB))) / 2.0
24+
} else {
25+
return Double(max(maxLeftA, maxLeftB))
26+
}
27+
} else if maxLeftA > minRightB {
28+
r = pa - 1
29+
} else {
30+
l = pa + 1
31+
}
32+
}
33+
34+
return 0.0
35+
}
36+
}

0 commit comments

Comments
 (0)