I'm trying to solve leetcode problem 4 which needs you to do binary search.
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
This is my code:
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
if len(nums1) > len(nums2):
return self.findMedianSortedArrays(nums2, nums1)
A, B = nums1, nums2
total = len(A) + len(B)
half = total // 2
l, r = 0, len(A) - 1
while l < r:
i = l + (r - l) // 2
j = half - i - 1 - 1
Aleft = A[i] if i >= 0 else float("-inf")
Aright = A[i + 1] if (i + 1) < len(A) else float("inf")
Bleft = B[j] if j >= 0 else float("-inf")
Bright = B[j + 1] if (j + 1) < len(B) else float("inf")
if Aleft <= Bright and Bleft <= Aright:
if total % 2:
return min(Aright, Bright)
else:
return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
elif Aleft > Bright:
r = i - 1
elif Bleft > Aright:
l = i + 1
It gives this error note:
TypeError: None is not valid value for the expected return type double
raise TypeError(str(ret) + " is not valid value for the expected return type double");
Line 52 in _driver (Solution.py)
_driver()
Line 59 in <module> (Solution.py)
During handling of the above exception, another exception occurred:
TypeError: must be real number, not NoneType
Line 18 in _serialize_float (./python3/__serializer__.py)
Line 61 in _serialize (./python3/__serializer__.py)
out = ser._serialize(ret, 'double')
Line 50 in _driver (Solution.py)
However if I change the while loop condition to just while True:
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
if len(nums1) > len(nums2):
return self.findMedianSortedArrays(nums2, nums1)
A, B = nums1, nums2
total = len(A) + len(B)
half = total // 2
l, r = 0, len(A) - 1
while True:
i = l + (r - l) // 2
j = half - i - 1 - 1
Aleft = A[i] if i >= 0 else float("-inf")
Aright = A[i + 1] if (i + 1) < len(A) else float("inf")
Bleft = B[j] if j >= 0 else float("-inf")
Bright = B[j + 1] if (j + 1) < len(B) else float("inf")
if Aleft <= Bright and Bleft <= Aright:
if total % 2:
return min(Aright, Bright)
else:
return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
elif Aleft > Bright:
r = i - 1
elif Bleft > Aright:
l = i + 1
It runs perfectly. Why the difference? How could these two different in logic? Any help will be much appreciated.