LeetCode01--寻找两个有序数组的中位数
1 ''' 2 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 3 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 4 你可以假设 nums1 和 nums2 不会同时为空。 5 示例 1: nums1 = [1, 3] nums2 = [2] 则中位数是 2.0 6 示例 2: nums1 = [1, 2] nums2 = [3, 4] 则中位数是 (2 + 3)/2 = 2.5 7 ''' 8 9 10 class Solution: 11 12 def findMedianSortedArrays(self, nums1, nums2): 13 """ 14 :type nums1: List[int] 15 :type nums2: List[int] 16 :rtype: float 17 """ 18 nums1.extend(nums2) 19 res = nums1 20 if not res: 21 return None 22 res.sort() 23 l = len(res) 24 if l % 2: 25 return res[int((l-1) / 2)] 26 else: 27 return (res[int(l / 2)] + res[int((l / 2) - 1)]) / 2.0 28 29 30 if __name__ == '__main__': 31 n1 = [1, 3] 32 n2 = [2, 3] 33 num = Solution().findMedianSortedArrays(n1, n2) 34 print(num)