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

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

相关推荐
执风挽^10 分钟前
Python基础编程题2
开发语言·python·算法·visual studio code
Z9fish20 分钟前
sse哈工大C语言编程练习20
c语言·开发语言·算法
晓131325 分钟前
第六章 【C语言篇:结构体&位运算】 结构体、位运算全面解析
c语言·算法
iAkuya31 分钟前
(leetcode)力扣100 61分割回文串(回溯,动归)
算法·leetcode·职场和发展
梵刹古音34 分钟前
【C语言】 指针与数据结构操作
c语言·数据结构·算法
VT.馒头40 分钟前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
CoderCodingNo2 小时前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
大闲在人2 小时前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
小熳芋2 小时前
443. 压缩字符串-python-双指针
算法
Charlie_lll3 小时前
力扣解题-移动零
后端·算法·leetcode