合并2个排序链表--leecode

剑指offer:合并两个排序的链表 python实现 合并K个排序的链表 题目 题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 对应LeetCode21. 解题思路 暴力求解: 新建一个链表; 依次判断两个链表的大小,选择小的构建,直至结束。 # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.... 阅读详情

递归求解:

    public static ListNode mergeTwoListNode(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return (l1 == null) ? l2 : l1;
        }
        if (l1.val <= l2.val) {
            l1.next = mergeTwoListNode(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoListNode(l1, l2.next);
            return l2;
        }
    }

迭代法:

    static ListNode combineListNodeTraverse(ListNode node1, ListNode node2) {
        if (node1 == null || node2 == null) {
            return node1 == null ? node2 : node1;
        }
        ListNode head = null;
        ListNode tem = null;
        while (node1 != null && node2 != null) {
            if (node1.val <= node2.val) {
                if (head == null) {
                    head = tem = node1;
                } else {
                    tem.next = node1;
                    tem = tem.next;
                }
                node1 = node1.next;
            } else {
                if (head == null) {
                    head = tem = node2;
                } else {
                    tem.next = node2;
                    tem = tem.next;
                }
                node2 = node2.next;
            }
        }
        if (node1 == null) {
            tem.next = node2;
        } else {
            tem.next = node1;
        }
        return head;
    }

个人才疏学浅、信手涂鸦,更多内容持续更新中,感兴趣的朋友请移步至个人公众号,谢谢支持😜😜......

公众号:wenyixicodedog

自然合并排序 这是一个实现自然合并排序算法的c++程序,可助于大家参考。 立即下载

相关推荐

LabVIEW与三菱PLC通讯实战:ActiveX控件在FX5U上的应用技巧

本文深入探讨了如何利用三菱MX Component中的ActiveX控件,在LabVIEW中实现与FX5U系列PLC的高效、稳定通讯。文章从环境配置、ActiveX控件生命周期管理、数据读写性能优化及容错机制等实战角度,分享了构建工业级健壮通讯程序的核心技巧与架构设计思路。

qsc9012345的博客 889

LeetCode T21_mergeTwoLists

思路:让指针l1,l2(没有显示定义)分别指向L1,L2链表,依次比较L1与L2对应节点上的值,将较小的值存入最后要返回的链表m中,并让指向该链表的指针后移1位,和指向链表m的指针p后移1位,再次进行比较...... 视频讲解:https://www.bilibili.com/video/av27108858?from=search&seid=7060049135870917198 ...

菜鸟学编程 3946

kaggle竞赛平台上数据集下载详解

从kaggle 网站上下载数据集既保证了速度又避免了网络的不稳定造成下载失败问题。该平台也可以上传代码作为自己的代码库,不过本人更习惯将代码上传到github上。希望本人整理的kaggle库使用技巧能够帮助到正在阅读本博客的你。此外还有一篇博客针对kaggle数据集下载问题的几个问题的相关文章进行了整理【博客链接】。

li1784506的博客 2万+

mergeTwoList

这个是关于两个链表按顺序合并的问题,首先需要判这两个链表中是否存在空链表,定义了一个空链表l,并用a指向该空链表 1,比较链表当前元素的大小,将l指向小数,并记录下小数链表的next位置 2,判断哪个链表不为空,直接加到l后面 class ListNode(object): def __init__(self, x): self.val = x s

jiangjispe的博客 876

离合器KP点自学习:从原理到工程实践的全景解析

本文全面解析了离合器KP点自学习的原理与工程实践,详细介绍了KP点的物理本质、控制价值及自学习方法。通过扭矩增量式和转速变化式学习法,结合不同变速箱构型的适配策略,提升离合器控制的精度与效率。文章还探讨了液压系统迟滞补偿和摩擦材料老化应对方案,为工程实践提供可靠保障。

weixin_33717117的博客 287

Dify 本地部署教程

到这里,Dify 就安装完成了,更多操作设置可以参考官方文档,Dify 和 FastGPT 基本上差不多,也可以同时安装一下 FastGPT 进行体验~Docker Compose 部署 | Dify。

Muti-Agent 6653

merge two list

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode { int val; struct ListNode *next; }; #define INT_MI

outlier的博客 552

《UDS协议从入门到精通》系列——图解0x83:访问时间参数

详细介绍UDS协议0x83服务,目标ECU的时序参数设置有哪些注意点?

车载系统攻城狮 2138

链表和归并排序(Merge Sort)

归并排序适合于对链表进行原址排序,即只改变指针的连接方式,不交换链表结点的内容。 归并排序的基本思想是分治法:先把一个链表分割成只有一个节点的链表,然后按照一定顺序、自底向上合并相邻的两个链表。 只要保证各种大小的子链表是有序的,那么最后返回的链表就一定是有序的. 归并排序分为分割和合并两个子过程。分割是用递归的方法,把链表对半分割成两个子链表;合并是在递归返回(回朔)的时候,把两个有序链表

Dread_naught的专栏 5656

【EMC专题】为什么芯片规格书ESD性能中看不到MM(机器放电模型)

器件级ESD包括三种类型,HBM人体放电模型、MM机械放电模型和CDM元件充电模型。但在芯片规格书中为什么只见到HBM模型与CDM模型,却没有看到MM模型的数据?

一点硬件 450

【温室气体数据集】全球总碳柱观测网络 TCCON

【温室气体数据集】全球总碳柱观测网络 TCCON

WW、forever的博客 437

Leetcode25.合并两个排序的链表

题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 完整代码 /* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode...

yyf_blog 436

22h2版本的win10安装Docker Desktop时页面空白

摘要:Windows10 22H2系统重装Docker时出现安装界面卡死问题,通过管理员CMD执行静默安装命令解决。命令指定了WSL-2后端及多个自定义数据存储路径(安装目录、Hyper-V数据、Windows容器数据、WSL数据),安装需等待几分钟。最终验证安装成功。

猿小白的博客 662

Java实现 LeetCode 23 合并K个排序链表

23. 合并K个排序链表 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/m...

南 墙 1万+

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

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

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

Leecode 148. 排序链表

题目描述 在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。 示例 1: 输入: 4->2->1->3 输出: 1->2->3->4 示例 2: 输入: -1->5->3->4->0 输出: -1->0->3->4->5 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sort-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请

Kingsley's Blog 5028

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

Leecode hot100 - 148. 排序链表

给你链表的头结点head,请将其按排列并返回。

2301_79601111的博客 744

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

leecode23 合并K个排序链表

  /**  * Definition for singly-linked list.  * public class ListNode {  *     int val;  *     ListNode next;  *     ListNode(int x) { val = x; }  * }  */ class Solution {     public ListNode merge2Li...

fyyf168lee的博客 175

LeetCode 合并K个排序链表

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1-&amp;amp;gt;4-&amp;amp;gt;5, 1-&amp;amp;gt;3-&amp;amp;gt;4, 2-&amp;amp;gt;6 ] 输出: 1-&amp;amp;gt;1-&amp;amp;gt;2-&amp;amp;gt;3-&amp;amp;gt;4-&amp;amp;gt;4-&a

hestyle的博客 569

K个排序链表的合并

问题描述; 合并k个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problem...

gw_9527的博客 623

Leecode day3——合并K个排序链表

1、Description 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 (来源于Leecode) 2、Example 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 3、Code # Definition ...

F_MILK_的博客 207

Leecode23. 合并k个排序链表

题目: 合并k个排序链表,返回合并后的排序链表,请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 解法一:(暴力求解): 1、首先创建一个空列表temp,将用于合并的k个链表全部存放到其中; 2、创建一个空节点h...

weixin_43763859的博客 138

LeetCode(C++)刷题计划:23-合并K个排序链表

23-合并K个排序链表 @Author:CSU张扬 @Email:csuzhangyang@gmail.com or csuzhangyang@qq.com Category Difficulty Pass rate Tags Companies algorithms Medium 72.20% linked-list / divide-and-conquer / heap a...

神奇小海螺的博客 9362

LeetCode实战:合并K个排序链表

题目英文 Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->...

老马的程序人生 836

合并k个有序链表 python_leecode刷题(27)-- 合并k个排序链表

leecode刷题(27)-- 合并k个排序链表合并k个排序链表合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。示例:输入:[1->4->5,1->3->4,2->6]输出: 1->1->2->3->4->4->5->6思路以前做过合并两个有序链表的问题,所以刚开始想到的解法与之类似,我们可以先合并两个有...

weixin_39713841的博客 215

go语言LeeCode刷题记:23. 合并K个排序链表

23. 合并K个排序链表 合并k个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 答案: /** * Definition for singly-linked l...

Duan_YZ的博客 320

Leetcode【分治 链表】| 23. 合并K个排序链表

Leetcode | 23. 合并K个排序链表题目解题顺序依次合并合并2链表递归实现合并2链表迭代实现两两成对合并(分治) 题目 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例:  输入:   [    1->4->5,    1->3->4,    2->6   ]  输出: 1->1->2->3->4-...

Cherils的博客 435
上一篇: 数组中的第K个最大元素--leecode 分治算法求解
下一篇: 合并K个排序链表--leecode
wenyixicodedog
博客等级 码龄8年 87粉丝 116原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值