寻找两个正序数组的中位数

题目

给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 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


来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/median-of-two-sorted-arrays

代码

  • 时间复杂度为 O(m+n)
class Solution {
  double findMedianSortedArrays(List<int> nums1, List<int> nums2) {
    List<int> list = nums1 + nums2;
    if (list.isEmpty) return 0;
    if (list.length == 1) return list.first.toDouble();
    if (list.length == 2) return (list.first + list.last) / 2;
    list.sort();
    int index = list.length ~/ 2;
    if (list.length % 2 == 0) {
      return (list[index - 1] + list[index]) / 2;
    } else {
      return list[index].toDouble();
    }
  }
}
  • 时间复杂度为 O(log (m+n))
这个太难了,暂时不会😭

解题思路

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容