【算法题】合并两个有序列表

两个有序表的合并(三种方法) 设有两个递增排列的有序表,要求合并后仍按递增(非递减)有序排列 阅读详情

① 合并到新队列 

 代码:

In [1]: def merge(lsta, lstb):
   ...:     merged = []
   ...:     while lsta and lstb:
   ...:         if lsta[0] < lstb[0]:
   ...:             merged.append(lsta.pop(0))
   ...:         else:
   ...:             merged.append(lstb.pop(0))
   ...:     return merged + lsta + lstb
   ...:

In [2]: merge([3,5,8,9,14], [2,3,7,9,15,17])
Out[2]: [2, 3, 3, 5, 7, 8, 9, 9, 14, 15, 17]

 ② 将一个列表合并到另一个列表

遍历列表1中的数据,将其全部插入列表2的正确位置即可。

In [8]: def merge_to(lsta, lstb):
   ...:     def insert(n, tar):
   ...:         idx = 0
   ...:         while idx < len(lstb) and n > tar[idx]:
   ...:             idx += 1
   ...:         tar.insert(idx, n)
   ...:     for num in lsta:
   ...:         insert(num, lstb)

In [9]: lst = [2,3,7,9,15,17]

In [10]: merge_to([3,5,8,9,14], lst)

In [11]: lst
Out[11]: [2, 3, 3, 5, 7, 8, 9, 9, 14, 15, 17]

 

力扣 P21 合并两个有序列表 合并两个有序列表 题目 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 解题思路 先判断L1,L2是否为空,接下来通过循环来将两个列表中的元素按从小到大进行合并,最后返回的列表即为所求得的合并的列表。 代码实现 运行结果 这个方法思路简单, 立即下载

相关推荐

别再只放按钮了!巧用微信小程序‘长按识别’功能,打造无缝加群体验

本文深入探讨了微信小程序'长按识别'功能在社群运营中的创新应用,通过简化加群流程至一步操作,显著提升用户转化率。文章详细解析了技术实现细节、UI/UX设计策略,并对比了与企业微信API的适用场景,为开发者提供打造无缝加群体验的完整解决方案。

weixin_42627853的博客 434

合并有序列表

### 解题思路新建一个链接点pre。l1与l2的value比较,pre的next链接小的那个节点。节点向下移动一个,重复操作。当l1和l2中其中一个为null时,循环终止。找到另外一个还剩节点的链表,合并完。

weixin_53998810的博客 281

直线型一阶倒立摆1---从理论到实践的桥梁

本文深入探讨了直线型一阶倒立摆在控制理论中的核心地位,从非线性控制、鲁棒性到实时反馈等关键问题。通过实际案例和硬件搭建指南,帮助读者理解从理论到实践的过渡,特别适合控制工程初学者和研究人员。文章还提供了算法选型建议和硬件避坑手册,是掌握倒立摆控制的实用指南。

weixin_29047545的博客 318

有序表的合并

用顺序表和链式表两种方式实现有序表的合并

qq_74297147的博客 3035

[LaTeX] 调整参考文献的格式(References),包括作者名缩写,行距,字体,引用顺序等等

在此记录我对LaTeX中参考文献references的尝试,主要涵盖如题几个方面。

the Blog of 等不到天亮丶等时光 4万+

STM32与AD7606的SPI通信优化:提升高精度数据采集效率

本文深入探讨了STM32与AD7606的SPI通信优化策略,旨在提升高精度数据采集系统的效率与稳定性。文章从硬件连接、电源去耦、PCB布局等基础环节入手,详细解析了软件驱动中SPI模式配置、DMA应用及精准时序控制等关键优化技术,并提出了系统级的性能提升方案,帮助开发者解决高速采样下的数据跳动、效率瓶颈等实际问题。

weixin_29192211的博客 392

数据结构——有序顺序表的合并

以下是数据结构中关于有序顺序表的合并的基础操作(编程风格参考严蔚敏版数据结构)。 说明:ElemType 定义为int的目的是方便以后同意我们所需定义的元素的类型,比如如果以后想把结构体内的元素类型改为char,只需要在ElemType 这里宏定义为char即可(当然,编程的过程中关于元素的类型也要写ElemType) 初始化 特别注意:这里传进来的是一个实体,如果传进来的是指针,要先给指针开辟内存空间:L = new Sqlist; 说明:书本上的代码是简写,关于声明的部分猜测是因为篇幅并没有写出来..

qq_51231048的博客 8646

Linux系统搭建OpenClaw(原Clawdbot)全流程指南 最新版

工具定位:开源个人 AI 助手,支持文件读取、命令执行、多渠道交互(Telegram / 本地终端等);系统要求:主流 Linux 发行版(Ubuntu/Debian/CentOS 等),Node.js ≥22(核心依赖);安全提示:OpenClaw 为测试版,具备高权限操作能力,建议使用非主力机,配置权限白名单,避免接触敏感数据。

AI时代老码农的第二春 6560

【数据结构之线性表】有序表的合并(链表篇)

将链表L1和L2按照顺序合并到L3中(注:三个链表都是带头结点的)其中:指针q:指向要插入L3中的结点,这里q=L1->next指针p3:始终指向L3的最后一个结点,方便后续结点插入图中步骤如下:①删除q指针指向结点前面的指针②删除q指针指向结点的后一个指针(相当于把q指向的结点给空出来)③直接移动L3头结点的指针,把q所指的结点接在L3后面p3->next=q④移动p3,使得p3始终指向L3的最后一个结点,方便后续结点插入。

2301_79982543的博客 1346

100天精通Python(进阶篇)——第43天:批量将PDF转Word文档(附上脚本代码)

100天精通Python(进阶篇)——第43天:批量将PDF转Word文档(附上脚本代码)

努力让自己发光,对的人才能迎着光而来 9万+

OpenStack [ compute_id ] 设计上的小缺陷

而 nova 代码中硬编码(或默认配置)将 compute_id 放在 site-packages 目录,属于 设计上的小缺陷—— 把 “库安装目录” 和 “运行时数据目录” 混在一起了,才导致需要临时调整这个目录的权限。# 配置项说明:node_identity_file 是 nova 用于指定节点标识文件路径的官方配置项,优先级高于代码中的默认路径。自定义 compute_id 路径,指向 /var/lib/nova/ 目录下的 compute_id 文件;

求知若渴,虚心若愚。 491

算法题_两个有序列表的合并

算法题目_单链表_合并两个有序链表

DreamsArchitects的博客 635

28.Anaconda安装jupyter notebook、jupyterlab及体验

手贱,不小心将Anaconda自带得jupyter给卸载了,没法子了查了好多资料都比较麻烦,所以自己摸索着重新安装,记录一下心得。说明:Anaconda没有加入环境变量,Anaconda官方建议不要将Anaconda加入环境变量,这就意味着他和python是可以共存的。

迷逝 5028

算法题:合并两个有序列表

说明:这篇文章是学习交流,转载请注明出处。欢迎转载! 题目:已知有两个有序的单链表,其头指针分别为head1和head2。实现将这两个链表合并的函数: Node* ListMerge(Node *head1,Node *head2) 这个算法非常像我们排序算法中的归并排序。仅仅能说“非常像”,由于思想是一样的,...

weixin_30376163的博客 132

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

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

深度学习工具包 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")

python 算法题-合并两个有序列表

【代码】python 算法题-合并两个有序列表。

weixin_47347921的博客 209

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Leetcode算法题(八)---------合并两个有序列表

Leetcode算法题(八)---------合并两个有序列表 题目:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 一.我的解法 public class MyTest8 { public static void main(String[] args) { //合并两个有序链表

weixin_39289579的博客 507

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

LeetCode算法题Day4

给你一个链表,删除链表的倒数第n个结点,并且返回链表的头结点。先遍历一下链表看有几个结点,然后再遍历一遍进行删除。

m0_74235082的博客 316

第一遍Leetcode——链表(1)/ 第一天1/3 2/3

按顺序的这条伟大航路先放弃了,四月第一天开始按类别做题:第一天在平台上做,大概率是要参考别人的思路的,第二天按理解的思路自己手写实现一遍,第三天再在博客上重做一遍要平台AC(也不知道要花多久,有复习的日子能不能完成7,anyway,要对自己狠一点motivation, dedication, hardworking can do anything,白天要完成然后晚上上课,不要怂呀///加油4月,这...

qq_37299596的博客 185

ARTS打卡3-小试无服务器架构

Algorithm做算法题,Review点评英文文章,Tip总结技术技巧,Share做技术分享。每周打卡一次,这就是ARTS打卡。 1. 做算法题 LeetCode第21题,合并两个有序列表 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->...

Andytl的博客 193

合并两个有序列表

本来很简单一题,很久没写算法题了居然在细节上纠结了我好久,唉~ 这种简单题就应该用简单的思路来做…在这也提醒各位,有的题真的只是看起来容易,真的写起来又会有好多乱七八糟的问题了。 闲话少说,上题吧,这是leetcode的第21题,各位可以去网站上面刷刷,经过那个测试才知道你的代码会不会有你没发现的问题。 分析: 首先,题目所给的函数如下,返回是一个指针,如果我在函数内部动态malloc一个链表,...

吟游诗人——吟唱生命的不朽 882

【算法题】合并两个有序数组

通过对合并两个有序数组这一问题的深入探讨,学习了三种不同的解题方法:直接合并后排序、双指针法以及逆向双指针法。直接合并后排序 简单直观,易于理解,但效率较低,时间复杂度为 O((m+n)log(m+n))。双指针法 利用了数组的有序性,通过两个指针分别遍历两个数组,实现了 O(m+n) 的时间复杂度,但需要额外的 O(m+n) 空间来存储结果。逆向双指针法 在双指针法的基础上进行了优化,避免了额外的空间开销,实现了原地合并,空间复杂度降为 O(1),是本题的最优解法。

Lion_Long的博客 1471

LeetCode 9 合并两个有序列表

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 自己编写的代码:/** * Definition for singly-linked list. * public cl...

a22184812的博客 158

千问 LeetCode 3801. 合并有序列表的最小成本 Rust实现

寻找多个有序列表合并后的中位数,可以利用二分查找:在值域内二分一个数 mid,通过在每个列表中二分统计小于等于 mid 的元素个数,从而判断 mid 是否是中位数。- 初始状态:当 mask 只包含一个列表时(即 __builtin_popcount(mask) == 1),不需要合并,成本为 0。- 状态转移:对于当前的 mask,我们可以枚举它的一个非空真子集 j,那么剩下的部分就是 k = mask ^ j。// 枚举子集 (经典子集枚举技巧: j = (j - 1) & mask)

m0_37843156的博客 158

【算法面试题python】合并k个有序列表

题目:合并k个有序list 输入:[[3,4,5], [1,6], [2,6,7,8], [5,6,9]] 输出:[1, 2, 3, 4, 5, 5, 6, 6, 6, 7, 8, 9] 思路:为每个list分配一个指针,每次循环比较k个指针指向的元素,取最小的放入新列表,退出循环的条件是所有列表的元素都被取完 代码: def merge(a): new = [] idx = [0]*len(a) # k个指针 while True: curmin = 1e6

baoxin1100的博客 632

算法练习——合并有序列表 leetcode.21 python

题目描述: 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 方法一:双指针(三指针) class ListNode: # 单链表的结点 def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListN

tangchujiang的博客 553
上一篇: 【算法题】使用两个栈实现一个队列
下一篇: 【Redis】redis为什么那么快
be5yond
博客等级 码龄10年 590粉丝 123原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值