[leetcode 004] 寻找两个有序数组的中位数

题目:给定两个有序数组,找出它们合并后所得数组的中位数。

例如:

nums1=[1,3]

nums2=[2]

中位数为2;

nums1=[1,2]

nums2=[3,4]

中位数为: (2+3)/2=2.5.

  

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
      nums1.extend(nums2)
      nums=sorted(nums1)
      num=len(nums)
    
      if  num %2 ==0:
         return (nums[int(len(num)/2)]+nums[int(len(num)/2)-1])/2
      else:
         return nums[int(len(num+1)/2]
         

猜你喜欢

转载自www.cnblogs.com/statlearning2019/p/10329085.html
今日推荐