LeetCode: 4. Median of Two Sorted Arrays

LeetCode - The World's Leading Online Programming Learning Platform

题目大意

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。

请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

解题思路

一、最容易想到的办法是把两个数组合并,然后取出中位数。但是合并有序数组的操作是 O(m+n) 的,不符合题意。看到题目给的 log 的时间复杂度,很容易联想到二分搜索。

复制代码
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int size = nums1.length + nums2.length;
            int index1 = 0;
            int index2 = 0;
            int end = size/2;
            int begin = end;
            if (size % 2 == 0) {
                begin = begin-1;
            }
            int [] result = new int[end];

            int index = 0;
            while (index1 + index2 < size && index <= end) {
                if (index1 > nums1.length - 1) {
                    result[index++] = nums2[index2++];
                    continue;
                }
                if (index2 > nums2.length - 1) {
                    result[index++] = nums1[index1++];
                    continue;
                }
                if (nums1[index1] <= nums2[index2]) {
                    result[index++] = nums1[index1++];
                    continue;
                }
                result[index++] = nums2[index2++];
            }
            return (result[begin] + result[end])/2d;
    }
}

二、去中位进行两个数组移动

相关推荐
wallflower20208 分钟前
滑动窗口算法在前端开发中的探索与应用
前端·算法
林木辛9 分钟前
LeetCode热题 42.接雨水
算法·leetcode
MicroTech202536 分钟前
微算法科技(NASDAQ: MLGO)采用量子相位估计(QPE)方法,增强量子神经网络训练
大数据·算法·量子计算
星梦清河39 分钟前
宋红康 JVM 笔记 Day15|垃圾回收相关算法
jvm·笔记·算法
货拉拉技术1 小时前
揭秘语音交互的核心技术
算法
矛取矛求1 小时前
日期类的实现
开发语言·c++·算法
在下雨5992 小时前
项目讲解1
开发语言·数据结构·c++·算法·单例模式
Jayyih2 小时前
嵌入式系统学习Day36(简单的网页制作)
学习·算法
脑洞代码2 小时前
20250909的学习笔记
算法
Christo32 小时前
TFS-2003《A Contribution to Convergence Theory of Fuzzy c-Means and Derivatives》
人工智能·算法·机器学习