There are two sorted arrays nums1 and nums2 of size m and n respectively.
Example 1: nums1 = [1, 3] nums2 = [2]
Code
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
n1 = len(nums1)
n2 = len(nums2)
i = 0
j = 0
sumpointer = 0
while (i < n1 or j < n2) and sumpointer <= (n1 + n2) >> 1:
if i >= n1:
j+=1
elif j >= n2:
i+=1
elif nums1[i] <= nums2[j]:
i+=1
else:
j+=1
sumpointer+=1
even = (n1 + n2) % 2 == 0
i-=1
j-=1
if i < 0:
return (nums2[j - 1] + nums2[j]) / 2.0 if even == True else nums2[j]
if j < 0:
return (nums1[i - 1] + nums1[i]) / 2.0 if even == True else nums1[i]
if even==False:
return max(nums1[i], nums2[j])
if nums1[i] < nums2[j]:
if j - 1 >= 0 and nums1[i] <= nums2[j - 1]:
return (nums2[j - 1] + nums2[j]) / 2.0
return (nums1[i] + nums2[j]) / 2.0
if i - 1 >= 0 and nums2[j] <= nums1[i - 1]:
return (nums1[i - 1] + nums1[i]) / 2.0
return (nums1[i] + nums2[j]) / 2.0