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

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

相关推荐
嘴贱欠吻!2 小时前
Flutter鸿蒙开发指南(七):轮播图搜索框和导航栏
算法·flutter·图搜索算法
张祥6422889042 小时前
误差理论与测量平差基础笔记十
笔记·算法·机器学习
踩坑记录2 小时前
leetcode hot100 2.两数相加 链表 medium
leetcode·链表
qq_192779873 小时前
C++模块化编程指南
开发语言·c++·算法
cici158744 小时前
大规模MIMO系统中Alamouti预编码的QPSK复用性能MATLAB仿真
算法·matlab·预编码算法
历程里程碑5 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
2501_940315266 小时前
航电oj:首字母变大写
开发语言·c++·算法
CodeByV6 小时前
【算法题】多源BFS
算法
TracyCoder1236 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
浒畔居6 小时前
泛型编程与STL设计思想
开发语言·c++·算法