題目鏈接https://leetcode.com/problems/median-of-two-sorted-arrays/description/
- 題目描述
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)).
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
- 題目大意
給出兩個排序鏈表,給出兩個鏈表合併後的中位數,時間複雜度應該爲 O(log (m+n))。
- 分析
這道題的難點在於時間複雜度的要求。直接想出時間複雜度爲O(log (m+n))的算法有點難度,先嚐試一種簡單的方法:
把兩個鏈表連接起來,再排序,輸出中位數即可,主要時間消耗在排序上,網上查閱可知鏈表的排序算法時間複雜度爲O((m+n)*log(m+n)),雖然沒有符合題目意思,也Accepted了。在Discuss模塊中有大神提供了一種O(log (min(m,n)))的方法https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2481/Share-my-O(log(min(mn))-solution-with-explanation
- 我的解法
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
num=nums1+nums2
num.sort()
# print((num))
numlen=len(num)
if (numlen==1):
return num[0]
elif (numlen==2):
return (num[0]+num[1])*0.5
elif (numlen%2==0):
return (num[int(numlen/2)]+num[int(numlen/2-1)])*0.5
else:
return num[int(numlen/2)]