I have spent hours debugging the following code, but I still cannot figure out where really breaks it. I feel the case ai+bi<=k is causing the error, but I don't know how to fix it. Can someone help?
Here is my code:
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
m, n = len(nums1), len(nums2)
mid1 = (m+n+1)//2
mid2 = (m+n+2)//2
return (self.getKth(nums1, nums2, mid1)+self.getKth(nums1, nums2, mid2))/2
# k one-indexed
def getKth(self, a, b, k):
if not a:
return b[k-1]
if not b:
return a[k-1]
ai, bi = (len(a)+1)//2, (len(b)+1)//2
ae, be = a[ai-1], b[bi-1]
if ai+bi<=k:
if ae<be:
return self.getKth(a[ai:], b, k-ai)
else:
return self.getKth(a, b[bi:], k-bi)
else:
if ae<be:
return self.getKth(a, b[:bi], k)
else:
return self.getKth(a[:ai], b, k)
Question: https://leetcode.com/problems/median-of-two-sorted-arrays/submissions/
Similar Solution(k is zero-based): https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2511/Intuitive-Python-O(log-(m%2Bn))-solution-by-kth-smallest-in-the-two-sorted-arrays-252ms