代码实现
解法一
用两个指针遍历两个数组,遍历一半数之后,就可以找到中位数了。
class Solution:
def isEven(self,number):
if number%2==0:
return True
return False
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
m=len(nums1)
n=len(nums2)
if n==0:
if self.isEven(m):
return (nums1[m//2-1]+nums1[m//2])/2
return nums1[m//2]
if m==0:
if self.isEven(n):
return (nums2[n//2-1]+nums2[n//2])/2
return nums2[n//2]
t=(m+n)//2
if self.isEven(n+m):
index1,index2=0,0
t_number1=0
t_number2=0
while index1<m or index2<n:
if index1<m and (index2>=n or nums1[index1]<nums2[index2]):
t_number1=t_number2
t_number2=nums1[index1]
index1=index1+1
elif index2<n and (index1>=m or nums1[index1]>=nums2[index2]):
t_number1=t_number2
t_number2=nums2[index2]
index2=index2+1
if index1+index2==t+1:
return (t_number1+t_number2)/2
else:
index1,index2=0,0
t_number=0
while index1<m or index2<n:
if index1<m and (index2>=n or nums1[index1]<nums2[index2]):
t_number=nums1[index1]
index1=index1+1
elif index2<n and (index1>=m or nums1[index1]>=nums2[index2]):
t_number=nums2[index2]
index2=index2+1
if index1+index2==t+1:
return t_number
其他的方法显得高端,水平暂时不够。
可以见:https://www.cnblogs.com/grandyang/p/4465932.html