题目:
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
代码:非递归思想,网站上提供的递归方法看不懂,本文用的方法时间复杂度满足要求,但是需要额外的内存开销。
思路很简单:遍历两个数组,按从小到大的顺序存在一个新数组中,遍历到第(m+n)/2个的时候停止,根据m+n是奇数还是偶数来从新数组中取出最后一个数,或者倒数两个数来计算中位数。
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
m, n = len(nums1), len(nums2)
count = 0 #记录已经合并的数组元素的个数
middle_index = (m+n)/2 #中间数字的下标
sort_num = [] #存储排序后的数字
i = j = 0 #分别遍历两个数组
while count <= middle_index :
if i < m and j < n :
if nums1[i] <= nums2[j] :
sort_num.append(nums1[i])
i += 1
else :
sort_num.append(nums2[j])
j += 1
elif i < m :
sort_num.append(nums1[i])
i += 1
elif j < n :
sort_num.append(nums2[j])
j += 1
count += 1
if (m+n)%2 == 1 :
return (sort_num[count-1]+sort_num[count-1])/2.0
else :
if m+n == 0 :
return "nums1 and nums2 are empty!"
else :
return (sort_num[count-1]+sort_num[count-2])/2.0