The method I implemented is:
first, except for special cases (such as an Inputlist is an empty list),
if it is a general case, the
quick sort method first sorts,
and then for the ordinary case (both lists are not empty),
my idea is that the two are first Then connect a long list
to this list,
if its length is odd, find it the smallest number of len // 2.
If its length is even, find its (len // 2)-1 smallest number and len // The average of 2 small numbers
The problem now turns to how to find the kth smallest number of an array.
Here, we use a method based on the quick sort method
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
len1 = len(nums1)
len2 = len(nums2)
if len1 == 0:
if len2 & 1 == 0:#偶数
return (nums2[len2//2]+nums2[(len2//2)-1])/2
else:
return nums2[len2//2]
if len2 == 0:
if len1 & 1 == 0:#偶数
return (nums1[len1//2]+nums1[(len1//2)-1])/2
else:
return nums1[len1//2]
sum_len = len1 + len2
if nums1[-1] <= nums2[0] or nums2[-1] <= nums1[0]:#list1的最后一个都没有list2的第一个大
sum_list = nums1 + nums2 if (nums1[-1] <= nums2[0]) else (nums2 + nums1)
if sum_len & 1 == 1:#odd
return sum_list[sum_len//2]
else:
return (sum_list[sum_len//2] + sum_list[(sum_len//2)-1])/2
sum_list = nums1 + nums2
if sum_len & 1 == 1:#奇数长度,取sum_len//2
val,_ = self.GetKthxiao(sum_list,sum_len//2)
return val#self.GetKthxiao(sum_list,sum_len//2)
elif sum_len & 1 == 0:#偶数长度
v1,paixu1 = self.GetKthxiao(sum_list,(sum_len//2)-1)
v2,paixu2 = self.GetKthxiao(paixu1[(sum_len//2):],0)
return (v1+v2)/2#(self.GetKthxiao(sum_list,sum_len//2) + self.GetKthxiao(sum_list,(sum_len//2)-1))/2
def swap(self,inputlist,s1,s2):
temp = inputlist[s1]
inputlist[s1] = inputlist[s2]
inputlist[s2] = temp
return inputlist
def Partition(self,inputlist,start,end,value):
#这个函数把inputlist里比value大的元素放其右边,把比value小的元素放其左边
#定义:指针cur:表示当前的游标
#定义:指针small:表示前small个数确保比value小。初值:start - 1
#定义:指针big:表示value及其后面的数字确保比value大。初值:end + 1
#cur从start开始
small = start - 1
big = end + 1
cur = start
length = len(inputlist)
while cur != big:
if inputlist[cur] > value:#当前数字大于mid数字
big -= 1
inputlist = self.swap(inputlist,cur,big)
elif inputlist[cur] < value:#当前数字小于mid数字
small += 1
inputlist = self.swap(inputlist,cur,small)
cur += 1
else:
cur += 1
return inputlist,small+1
def GetKthxiao(self,inputlist,K):
length = len(inputlist)
inputlist,index = self.Partition(inputlist,0,length-1,inputlist[0])
#代表inputlist[:index]都比inputlist[index]小
while True:
if index < K:
inputlist,index = self.Partition(inputlist,index+1,length-1,inputlist[index+1])
elif index > K:
inputlist,index = self.Partition(inputlist,0,index-1,inputlist[index-1])
elif index == K:
#代表inputlist[:K]都比inputlist[K]小
#inputlist[K]是inputlist第K小的数字
return inputlist[K],inputlist