There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
the main idea is if nums1_mid < nums2_mid nums1 = nums1_right_part nums2 = nums2_left_part
we need constant space and O(log(m+n)) time
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ nums1_length = len(nums1) nums2_length = len(nums2) left = (nums1_length + nums2_length + 1) / 2 right = (nums1_length + nums2_length + 2) / 2 return (self.getKth(nums1, 0, nums2, 0, left) + self.getKth(nums1, 0, nums2, 0, right)) / 2.0 #if nums1 mid < nums2 mid keep nums1 right + nums2 left def getKth(self, nums1, nums1_start, nums2, nums2_start, k): if nums1_start > len(nums1) - 1: return nums2[nums2_start + k - 1] if nums2_start > len(nums2) - 1: return nums1[nums1_start + k - 1] if k == 1: return min(nums1[nums1_start], nums2[nums2_start]) nums1_mid, nums2_mid = 1 << 31, 1 << 31 if nums1_start + k / 2 - 1 < len(nums1): nums1_mid = nums1[nums1_start + k / 2 - 1] if nums2_start + k / 2 - 1 < len(nums2): nums2_mid = nums2[nums2_start + k / 2 - 1] if nums1_mid < nums2_mid: return self.getKth(nums1, nums1_start + k / 2, nums2, nums2_start, k - k / 2) else: return self.getKth(nums1, nums1_start, nums2, nums2_start + k / 2, k - k / 2)