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;
    }
}

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

相关推荐
Voyager_424 分钟前
图像处理踩坑:浮点数误差导致的缩放尺寸异常与解决办法
数据结构·图像处理·人工智能·python·算法
文艺倾年30 分钟前
【八股消消乐】手撕分布式协议和算法(基础篇)
分布式·算法
万岳科技系统开发1 小时前
从源码优化外卖配送系统:算法调度、智能推荐与数据分析应用
算法·数据挖掘·数据分析
信奥卷王4 小时前
[GESP202503 五级] 原根判断
java·数据结构·算法
兮山与4 小时前
算法4.0
算法
nju_spy4 小时前
力扣每日一题(二)任务安排问题 + 区间变换问题 + 排列组合数学推式子
算法·leetcode·二分查找·贪心·排列组合·容斥原理·最大堆
初听于你4 小时前
高频面试题解析:算法到数据库全攻略
数据库·算法
翟天保Steven4 小时前
ITK-基于Mattes互信息的二维多模态配准算法
算法
代码对我眨眼睛4 小时前
226. 翻转二叉树 LeetCode 热题 HOT 100
算法·leetcode·职场和发展
黑色的山岗在沉睡5 小时前
LeetCode 494. 目标和
算法·leetcode·职场和发展