leetcode 兩個排序的中位數 python
阿新 • • 發佈:2018-10-11
假設 lee pytho per oat sorted tran -s rap
兩個排序數組的中位數
給定兩個大小為 m 和 n 的有序數組 nums1 和 nums2 。
請找出這兩個有序數組的中位數。要求算法的時間復雜度為 O(log (m+n)) 。
你可以假設 nums1 和 nums2 不同時為空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
中位數是 2.0
示例 2:
nums1 = [1, 2] nums2 = [3, 4] 中位數是 (2 + 3)/2 = 2.5
兩個列表合並一下排個序, 然後再找中位數
奇數個元素就返回中間元素
偶數個元素返回中間兩個的平均數
1 class Solution:
2 def findMedianSortedArrays(self, nums1, nums2):
3 """
4 :type nums1: List[int]
5 :type nums2: List[int]
6 :rtype: float
7 """
8 nums = nums1 + nums2
9 nums.sort()
10 l = len(nums)
11 if l % 2 == 0:
12 return (nums[int(l/2)] + nums[int(l/2-1)])/ 2
13 else:
14 return nums[int((l-1)/2)]
leetcode 兩個排序的中位數 python