Skip to content

Instantly share code, notes, and snippets.

@BryanJin
Created August 6, 2018 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BryanJin/409a6ef9a52d544621b6e0ca430b3762 to your computer and use it in GitHub Desktop.
Save BryanJin/409a6ef9a52d544621b6e0ca430b3762 to your computer and use it in GitHub Desktop.
Median of Two Sorted Arrays
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
if len(nums2) < len(nums1):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
imin, imax = 0, m
while imin <= imax:
i = int((imin + imax) / 2)
j = int((m + n + 1) / 2 - i)
if (i < m and nums2[j - 1] > nums1[i]):
imin = i + 1
elif (i > 0 and nums1[i - 1] > nums2[j]):
imax = i - 1
else:
maxLeft = 0
if i == 0:
maxLeft = nums2[j - 1]
elif j == 0:
maxLeft = nums1[i - 1]
else:
maxLeft = max(nums1[i - 1], nums2[j - 1])
if (m + n) % 2 == 1:
return maxLeft
minRight = 0
if i == m:
minRight = nums2[j]
elif j == n:
minRight = nums1[i]
else:
minRight = min(nums1[i], nums2[j])
return (maxLeft + minRight) / 2
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment