弟中弟的Leetcode总结——数组类(一)
题目描述
Median of Two Sorted Arrays
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)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
思路
假设将两个数列合并,那么最后的结果应该是中位数两边的数的个数相同。但是在这里其实不需要合并,可以对每个数列分别设置一个cut来模拟合并后的切割。
设cut1的左边值为L1,右边为R1;cut2的左边值为L2,右边为R2。只需要满足:
L1<=R2&&L2<=R1
那么就可以找到等价于合并后切割到中位数的方法。考虑到时间的限制,可以使用二分查找对较短的数列进行处理。
此外,还需要考虑边界的问题,也就是当cut的左边或者右边是边界的时候,需要设定左边或者右边的值为无穷大或者无穷小。
代码(py3)
使用了py3,写的很烂凑合看吧。。。有的地方为了写清楚用了很多ifelse
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
len1=len(nums1)
len2=len(nums2)
total_len=len1+len2
#对小的数列进行处理
if(len1>len2):
return self.findMedianSortedArrays(nums2, nums1)
#如果有一个空数列直接输出第二个的中位数
if(len1==0):
return float((nums2[int((len2-1)/2)]+nums2[int(len2/2)])/2)
#设定二分法的左右边界
left=0
right=len1
#设定cut的初始值
cut1=int(len1/2)
cut2=int(total_len/2)-cut1
while(cut1<=len1):
cut1=int((right-left)/2)+left
cut2=int(total_len/2)-cut1
L1=0
L2=0
R1=0
R2=0
#处理边界问题
if(cut1==0):
L1=-1000000
else:
L1=nums1[(cut1-1)]
if(cut1==len1):
R1=1000000
else:
R1=nums1[cut1]
if(cut2==0):
L2=-1000000
else:
L2=nums2[cut2-1]
if(cut2==len2):
R2=1000000
else:
R2=nums2[cut2]
#判断cut是否正确
if(L1>R2):
right=cut1-1
continue
elif(L2>R1):
left=cut1+1
continue
else:
#如果总长度为偶数,输出平均值
if(total_len%2==0):
L=max(L1,L2)
R=min(R1,R2)
return float((L+R)/2)
#为奇数直接输出R1,R2的小的那个
else:
return min(R1,R2)