LeetCode | 4. Median of Two Sorted Arrays

图解LeetCode4:Median of Two Sorted Arrays 文章目录理解题意思路1:最直观解法思路2:二分查找代码实现结论 Leetcode算法系列将详细讲解一些经典的面试算法题。 今天的算法是LeetCode中第四个题目,Median of Two Sorted Arrays,也就是给定两个有序数组求出中位数。   理解题意 首先给定的是两个有序数组,比如{1,3}以及{2},那么合并这两个数组就是{1,2,3},因此很显然中位数是2; 再给定... 阅读详情

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

思路:要求时间复杂度O(log(n+m)),所以考虑采用二分查找.
由于两个数组都是有序的,那么结合之后的中位数就是大数组中第K大的数.
这里要分奇偶讨论一下,不详细介绍.
假设两个数组 a 和 b.找到a 和 b 中第 k/2大的数 a[k/2-1]和 b[k/2-1];记为 t1 和t2.
1.若 t1 == t2,那么t1 就是要找的中位数;
2.若 t1 < t2,那么 a 数组的前 t1 个数绝对比中位数小(这里很容易证明),所以抛弃 a[0]~a[t1-1], b不变,进行下一轮的查找;
3.若 t1 > t2,那么类似 2 中的步骤.舍去 b 数组中的一些值.
4.注意边界条件的一些处理.

int get_kth(int a[],int b[],int lena,int lenb,int k)
{
    if(lena > lenb)//保证第一个数组元素更少
        return get_kth(b, a, lenb, lena, k);
    if(lena == 0)
        return b[k-1];
    if(k == 1)
        return min(a[0],b[0]);
    int mida = min(k/2,lena), midb = k-mida;
    if(a[mida-1] == b[midb-1])
        return a[mida-1];
    else if(a[mida-1] < b[midb-1])
        return get_kth(a+mida, b, lena-mida, lenb, k-mida);
    else
        return get_kth(a, b+midb, lena, lenb-midb, k-midb);
}

int min(int a,int b)
{
    return a<b?a:b;
}

double findMedianSortedArrays(int* nums1, int n, int* nums2, int m) 
{
    int sum = n+m;
    if(sum%2 == 1)//奇数
        return get_kth(nums1,nums2,n,m,sum/2+1);
    else
        return ((get_kth(nums1, nums2, n, m, sum/2))+(get_kth(nums1, nums2, n, m, sum/2+1)))/2.0;
}
STM32中RS485方向控制引脚应用详解 深入解析STM32如何通过GPIO控制RS485通讯的方向引脚,实现半双工通信的精准切换。重点讲解硬件连接与软件时序配合,确保rs485通讯稳定可靠,适用于工业控制等实际场景。 阅读详情

相关推荐

opencv的cmake报错

1、下载 ippicv_2021.8_win_intel64_20230330_general.zip、v0.1.2a.zip、opencv_videoio_ffmpeg.dll、opencv_videoio_ffmpeg_64.dll、ffmpeg_version.cmake。由于下载源在https://raw.githubusercontent.com,由于网络原因下载不顺畅,可以先找到文件下载到对应文件夹下,或者更改网络环境。ffmpeg_version.cmake文件,打开后显示如下, 另存即可。

nownow_的博客 1305

LeetCode 4. Median of Two Sorted Arrays题解

题目 4. Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m...

孑辞的博客 413

5分钟搞定kkFileView 4.4.0 Docker部署:小白也能上手的完整配置流程

本文提供了一份针对kkFileView 4.4.0版本的Docker部署完整指南。通过使用预构建的Docker镜像,即使是新手也能在5分钟内完成文件预览服务的搭建,涵盖从环境准备、镜像拉取、容器启动到服务验证的全流程,并分享了进阶配置与生产环境优化建议。

mango的博客 543

LeetCode 4. Median of Two Sorted Arrays 题解

本题是二分查找的经典问题,主要考察对二分查找算法的理解和应用。通过将问题转化为在两个有序数组中找到第 k 小的元素,我们可以使用二分查找来高效地解决这个问题。二分查找的核心思想是:使用两个指针分别指向查找区间的两端,计算中间位置,比较中间元素与目标值的大小,根据比较结果缩小查找区间,直到找到目标值或确定目标值不存在。这种方法的时间复杂度为 O(log(min(m, n))),适用于大规模有序数组的中位数查找。掌握二分查找的原理,对于理解搜索算法和算法设计思想非常重要。

cannonjinx的博客 1010

海思3516DV300智能算法实现

海思3516DV300智能算法实现

xiaoning132的专栏 939

图神经网络实战(21)——图神经网络的可解释性

在本节中,我们探讨了应用于图神经网络 (Graph Neural Networks, GNN) 的可解释性人工智能 (Explainable Artificial Intelligence, XAI) 技术。可解释性是许多领域的关键要素,可以帮助我们建立更好的模型。我们介绍了不同的局部解释技术,并重点讨论了 GNNExplainer (基于扰动的方法),在图分类任务中应用 GNNExplainer。

盼小辉丶的博客 9837

LeetCode-4. Median of Two Sorted Arrays [C++][Java]

Given two sorted arraysnums1andnums2of sizemandnrespectively, returnthe medianof the two sorted arrays. The overall run time complexity should beO(log (m+n)).

贫道绝缘子的博客 259

NeRF-Pytorch(训练自己的数据集过程全记录+环境配置+COLMAP+问题解决)

写于2025/1/26,在用NeRF训练自己的数据集过程中该踩的坑都踩过了,发现网上并没有详细完整写这些问题解决过程的帖子,遂自己进行一个全记录和复盘。 整篇文章包括:NeRF训练环境配置;COLMAP三维重建过程(直接给出代码,规避一些bug);在训练时候出现的问题。 本篇文章仅针对llff格式数据集。

m0_62577716的博客 1777

Leetcode 4 Median of Two Sorted Arrays

今天发现了leetcode上面一道题,觉得非常经典,记录之。 题目是这样的:给定两个已经排序好的数组(可能为空),找到两者所有元素中第k大的元素。另外一种更加具体的形式是,找到所有元素的中位数。本篇文章我们只讨论更加一般性的问题:如何找到两个数组中第k大的元素?不过,测试是用的两个数组的中位数的题目,Leetcode第4题 Median of Two Sorted Arrays 方案1:假

思维决定一切 3万+

基于NB-IoT的智慧路灯监控系统(NB-IoT专栏—实战篇1:项目简介)

基于NB-IoT技术的城市道路智慧路灯监控系统,在每个照明节点上安装一个集成了NB-IoT模组的单灯控制器,单灯控制器再经运营商的网络,与路灯控制平台实现双向通信,路灯控制平台直接对每个灯进行控制,包括开关灯控制、光照检测、自动调节明暗、电耗分析等操作。

不脱发的程序猿 5万+

2、微软 Power Automate 入门指南

本文是一篇关于微软 Power Automate 的入门指南,详细介绍了 Power Automate 的基本概念、相关术语、登录方式以及如何创建一个简单的自动化流。文章还探讨了 Power Automate 在业务流程中的应用场景和优势,并展望了其高级功能和未来发展。适合希望快速入门 Power Automate 并提升业务自动化效率的读者。

corn8的博客 453

Leetcode 4 median-of-two-sorted-arrays题解

Leetcode median-of-two-sorted-arrays题解 虽然很简单,但是值得纪念一下,第一次超过100%的人 题目链接 思路: **Talking is no use, show your my codes** 代码: class Solution { public double findMedianSortedArrays(int[] nums1, int[] n...

qq_42308861的博客 319

SAPFiori Elements Analytical List Page 概述

ALP(Analytical List Page)是SAP Fiori提供的一种复合页面类型,结合了分析(图表/KPI)与事务(表格/操作)功能,适用于需要分析后立即执行处理的业务场景(如采购价格监控、销售逾期处理等)。其核心价值在于让用户在同一页面完成从数据洞察到事务处理的闭环,减少应用切换带来的效率损耗。 页面结构包含页头KPI标签、交互式图表和明细表格,通过联动过滤、选择同步等机制实现数据钻取与即时操作。支持标准过滤和可视化过滤,并依赖OData注解(SelectionVariant/Presenta

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 285

Leetcode-4 Median of Two Sorted Arrays 做题总结

一、介绍 这是Leetcode中的第4个题目,可以说,很多按照顺序刷题的同学,刷着刷着,突然就碰到了这个题目,然后就懵逼了。特别是看到了上面说的时间复杂度限制为O(log (m+n))的时候,感觉难以下手。其实我也是哈哈哈,但我没有按照顺序做题,而是在顺序的基础上,做完一个题目之后,根据accepted页面下,Next challenges来做,如图所示: ...

一点点博客 396

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

LeetCode4. Median of Two Sorted Arrays

之前没钻研过LeetCode,上次做题时,以为要找什么类型的题目就在搜索栏输入对应的关键词,结果输入divide-and-conquer才搜到一题,后来经提醒才知道在网页右侧有个提供各种关键词的topics框部,点击了divide-and-conquer便搜到了好多道相关题目,方便许多。之前真是太蠢了。 这次选择的是第4题:Median of Two Sorted Arrays  难度系数为H

reborncgy的博客 356

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【LeetCode】解题4:Median of Two Sorted Arrays

LeetCode解题 4:Median of Two Sorted Arrays Problem 4: Median of Two Sorted Arrays [Hard]解题思路Solution (Java)修改过程 Problem 4: Median of Two Sorted Arrays [Hard] There are two sorted arrays nums1 and nums2 ...

Fayedily的博客 333

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

[leetcode] 4. Median of Two Sorted Arrays

Description There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume n...

Learning from the mistakes 264

【LeetCode】4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+...

zjwreal 390

LeetCode 4. Median of Two Sorted Arrays

题目: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 思路: 本题要求出两个有序数组的中位

wshish920907的博客 2073

LeetCode(4)Median of Two Sorted Arrays

题目There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).分析给定两个有序序列,要求两个序列综合后的中位数。关键:

指尖飞舞 2135

leetcode 4 Median of Two Sorted Arrays

题目:There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 看到题目,首先想到的是 把2个数组合并成一个,然后在去中间位

大三狗现在才努力还不算晚吧?! 3496

leetcode 4 median of two sorted arrays

leetcode 4 median of two sorted arrays本文给出leetcode第四题Median of Two Sorted Arrays的答案及所用到的简单知识总结,适用于C++初学者 本文代码下载地址目录leetcode 4 median of two sorted arrays目录 题目 插入法题目There are two sorted arrays nums1 an

Alice lr的博客 420

【LeetCode】4. Median of Two Sorted Arrays 递归

一、概述 给出两个有序数组,找它们的中位数。 时间复杂度要求O(log(m+n))。 二、分析 1、我的方法(没写代码,边界条件太多) 一看时间复杂度要求log,肯定是用二分。那么如何二分呢?想到正常二分法是一次劈一半长度,因此照着平常的思路去做,将长度减半。 维护四个变量,start1,start2,end1,end2。分别表示目前两个数组还剩的部分。 首先找到两个数组各自的中位数...

四轩茶屋 324
上一篇: 多重背包问题
下一篇: LeetCode | 3. Longest Substring Without Repeating Characters
PKU_CXK
博客等级 码龄10年 87粉丝 142原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值