解法一:双指针
复杂度(O(m+n))
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n1 = len(nums1)
n2 = len(nums2)
cnt = (n1+n2)//2 + 1
i = j = 0
m = []
while cnt>0:
cnt-=1
if i<n1 and j<n2:
if nums1[i]<=nums2[j]:
m.append(nums1[i])
i+=1
else:
m.append(nums2[j])
j+=1
elif i<n1:
m.append(nums1[i])
i+=1
else:
m.append(nums2[j])
j+=1
if (n1+n2)%2==0:
median = (m[-1]+m[-2])/2
else:
median = m[-1]
return median
解法二:
寻找两个数组中的第K大
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
n1 = len(nums1)
n2 = len(nums2)
if (n1+n2)%2==0:
return (self.findK(nums1,nums2,(n1+n2)//2+1) +self.findK(nums1,nums2,(n1+n2)//2))/2
else:
return self.findK(nums1,nums2,(n1+n2)//2+1)
def findK(self,nums1,nums2,k) :
if len(nums1)>len(nums2):
return self.findK(nums2,nums1,k)
if len(nums1)==0:
return nums2[k-1]
if k==1:
return min(nums1[0],nums2[0])
pa = min(k//2,len(nums1))
pb = k - pa
if nums1[pa-1]<nums2[pa-1]:
return self.findK(nums1[pa:],nums2,pb)
elif nums1[pa-1]>=nums2[pa-1]:
return self.findK(nums1,nums2[pa:],pb)