当前位置:   article > 正文

蓝桥杯训练--力扣4_力扣蓝桥杯

力扣蓝桥杯
4. 寻找两个正序数组的中位数

难度困难6295收藏分享切换为英文接收动态反馈

给定两个大小分别为 mn 的正序(从小到大)数组 nums1nums2。请你找出并返回这两个正序数组的 中位数

算法的时间复杂度应该为 O(log (m+n))

示例 1:

输入:nums1 = [1,3], nums2 = [2]

输出:2.00000

解释:合并数组 = [1,2,3] ,中位数 2

示例 2:

输入:nums1 = [1,2], nums2 = [3,4]

输出:2.50000

解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5

#思想

  1. 通过extend函数把nums2添加到nums1里面

  1. 用sort函数排序

  1. 找到中间位置的下标

  1. 偶数和奇数情况分俩种计算中位数

#代码

  1. class Solution:
  2. def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
  3. nums1.extend(nums2)
  4. nums1.sort()
  5. mid = len(nums1) // 2
  6. if len(nums1) % 2 == 0: #偶数
  7. ans = (nums1[mid] + nums1[mid-1]) / 2
  8. else:
  9. ans = nums1[mid]
  10. return ans

#运行结果

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/967630
推荐阅读
相关标签
  

闽ICP备14008679号