lc 148. 排序链表 ( bottom-up 归并排序

归并排序算法链表实现 归并排序的链表实现 随机生成实验数据,可以统计算法运行时间 立即下载

归并排序,如果不要求O(1)的空间复杂度,可以很简洁的完成:

找到当前链表的中点,然后对链表的两半递归的进行排序,merge

但是现在需要O(1)的空间,所以不能递归,选用自底向上的归并排序:

对原链表按不同的粒度进行划分,一开始粒度为1,然后进行merge

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    // bottom up的排序
    // cut:在第n个节点处断开,返回之后链表
    private ListNode cut(ListNode head,int n){
        ListNode p=head;
        while(n>1&&p!=null){
            n--;
            p=p.next;
        }
        if(p==null){
            return null;
        }
        ListNode t=p.next;
        p.next=null;
        return t;
    }
    private ListNode merge(ListNode a,ListNode b){
        // 尾插法即可
        ListNode dummy=new ListNode(0);
        ListNode t=dummy;
        while(a!=null&&b!=null){
            if(a.val<b.val){
                t.next=a;
                t=a;
                a=a.next;
            }else{
                t.next=b;
                t=b;
                b=b.next;
            }
        }
        if(a!=null){
            t.next=a;
        }
        if(b!=null){
            t.next=b;
        }
        return dummy.next;
    }

    public ListNode sortList(ListNode head) {
        int len=0;
        ListNode p=head;
        while(p!=null){
            p=p.next;
            len++;
        }
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        for(int sz=1;sz<len;sz=sz*2){
            ListNode t=dummy;
            p=dummy.next;
            while(p!=null){
                ListNode a=p;
                p=cut(p,sz);
                ListNode b=p;
                p=cut(p,sz);
                t.next=merge(a,b);
                while(t.next!=null){
                    t=t.next;
                }
            }
        }
        return dummy.next;
    }
}

注意cut中要注意对空指针的检查

【嵌入式Linux】EC20模块多运营商自适应PPP拨号实战:从IMSI识别到网络配置 本文详细介绍了在嵌入式Linux系统中,如何基于EC20 4G模块实现多运营商自适应PPP拨号。通过解析SIM卡的IMSI识别运营商,并动态配置对应的APN和拨号参数,结合AT指令交互与健壮的pppd脚本,解决了设备跨地域部署时的网络自动连接问题,提升了物联网设备的部署效率和稳定性。 阅读详情

相关推荐

若依(ruoyivue)实现文档在线查看

1、Kkfileview部署 第一步:从kkfileview官方发行版本下载安装包,安装包下载路径: https://gitee.com/kekingcn/file-online-preview/releases, 第二步:解压kkFileView-x.x.x文件(Windows用.zip包,Linux/MacOS用.tar.gz包) 第三步:打开解压后文件夹的bin目录,运行startup脚本(Windows下以管理员身份运行startup.bat,Linux以root用户运行startup.sh) 第四

weixin_46953697的博客 9681

剑指offer77:链表排序(归并排序)

题目: 给定链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。 输入:head = [4,2,1,3] 输出:[1,2,3,4] 输入:head = [-1,5,3,4,0] 输出:[-1,0,3,4,5] 分析: 代码:

L的博客 1953

CORS(跨域资源共享)漏洞解决方法

最近,测试环境上的项目被360测试人员检测出来有一个CORS漏洞,以下记录下漏洞问题与解决方法。 一、低危漏洞:CORS漏洞问题 测试人员访问某个url,将请求头中的Origin字段修改为任意值,结果仍然能获得正确的响应报文,就说明有CORS漏洞。 当CORS的设置不正确时,就会带来安全问题;当响应头中的Access-Control-Allow-Origin设置为null或*时,表示信任任何域,这时候就可能引入安全问题。 修复方法是合理配置CORS,判断Origin是否合法;具体说就是不让在nginx或t

BHSZZY的博客 3万+

链表排序:归并排序 - C语言实现

【代码】链表排序:归并排序。

weixin_50577609的博客 1293

PyFluent进阶实战:自动化密闭几何(Watertight)网格生成

本文深入探讨了如何利用PyFluent实现自动化密闭几何(Watertight)网格生成。通过Python脚本控制Fluent Meshing工作流,工程师可以高效、一致地完成从几何导入、局部尺寸定义、面网格生成到边界层设置和体网格输出的全过程,从而将复杂的CFD前处理工作转化为可重复、可集成的自动化流程,极大提升仿真效率和知识复用性。

t8u9v0w1x的博客 578

EDEM在农业机械设计中的实战应用:以谷物收割机优化为例

本文以谷物收割机优化为例,详细阐述了EDEM离散元仿真软件在农业机械设计中的实战应用。通过构建精准的“数字谷物”模型与农机部件动态界面,利用GPU加速完成大规模颗粒系统仿真,有效诊断并解决了籽粒夹带损失与清选负荷不均等田间难题,实现了从仿真分析到田间验证的设计优化闭环。

weixin_29256771的博客 109

LeetCode-归并排序链表

归并排序链表的两种实现方式---递归/迭代

xaiobit_hl的博客 1233

VINS-Fusion实战:从零搭建无人机视觉SLAM系统(附ROS配置全流程)

本文详细介绍了如何从零开始为无人机搭建基于VINS-Fusion的视觉SLAM系统。内容涵盖硬件选型(重点推荐双目相机与IMU搭配)、ROS环境配置、传感器标定、核心参数调优以及实际飞行测试与问题排解全流程,旨在帮助开发者实现稳定、精确的无人机自主定位与导航。

wasm7browser的博客 214

[LeetCode刷题笔记] 148.排序链表

学习自用 链接 148.排序链表 思路 归并排序(递归法) 对单链表排序首先想到归并排序(因为无法回访前驱节点,快排等算法无法使用,而归并排序的合并操作,单链表可以很好地完成。) 递归法步骤: 快慢指针法找到中间节点。 断链,并得到右侧链表头 递归排序左右链表 合并 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode

weixin_44080010的博客 221

A Mathematical Framework for Transformer Circuits—(一)

transformer数学理解理论

qq_42208244的博客 2663

在Pycharm中配置Pyqt5工具(2023年新版教程)

在Pycharm中配置Pyqt5相关的三个工具:QtDesigner、PyUIC、PYRCC

网络技术和Python 2万+

排序链表(归并排序)

本题要求在 O(n log n) 时间复杂度和常数级空间复杂度下。排序算法中,只有快排、堆和归并排序时间复杂度可以满足要求,但是快排时间复杂度不稳定而且空间复杂度不是常数,堆不适合链表,所以要想到归并排序 空间复杂度 log n...

weixin_44311466的博客 825

基于分水岭分割进行肺癌诊断

近年来,肺癌的发病率和病死率均迅速上升,目前已居所有癌症之首。随着肺癌病人数量的增加,医生对肺部 CT 图像进行研判的工作量也增加了不少,在这种情况下难免工作效率降低甚至会出现误诊。为了帮助医生减少重复性工作,对肺部 CT 图像进行计算机辅助检测的技术就被广泛应用于对肺癌的诊断和治疗过程中。医学 CT 图像处理主要是研究医学图像中的器官和组织之间的关系,并进行病理性分析。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 1568

java中实现归并排序与链表的使用

【代码】java中实现归并排序。

nbbzi的博客 987

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

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

归并排序【链表】

函数名为mergeSort,接受两个参数a和b,它们都是指向ListNode的指针,分别代表两个已排序的链表。这个函数通过逐个比较两个已排序链表中的节点,创建一个新的合并链表。它有效地处理了链表为空的情况,确保所有节点都被正确连接,并返回合并后的结果。

m0_71250630的博客 555

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Top-down与Bottom-up

简析 顾名思义,top-down是由上至下,而bottom-up由下至上的意思。其实,就我对本行业的理解,top = 目的(objective),bottom = 方法细节(action)。 因此,top-down是由目的开始,推到达到目的的方法与其细节。而bottom-up则是由要采取、或是能采取的行动开始思考,最后看这些行动是否能达到目的。 Top-down思考的人会先花很多时间在搞清楚目的与框架上,bottom-up的人则是通常先把要做的事情一个个列出来后,才思考这和原本的目的有什么关系。 举

WeisongZhao 1万+

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

高级排序 03 归并排序 Bottom Up

算法实现 用2层循环,而不是递归完成归并排序; 外层循环 sz 表示每次 merge 的2个有序数组的长度,可以理解成步长,从1开始,1, 2, 4, 8... 内层循环i表示每次merge操作的起点,1次merge迈2步(2个sz),1次merge受影响的总长度为2个步长,与sz对应依次为 2, 4, 8, 16...,i 的限制是小于n - sz ,...

乌鲁木齐001号程序员 198

链表的归并排序

链表的归并排序

m0_55747309的博客 2146

【刷题】LC 148. 排序链表

【刷题】LC 148. 排序链表

LifeIsGood 174

归并排序-bottom-up(非递归版本)

由于之前讨论的归并排序时用到的是递归的方法;而递归会带来很大的开销,本节讨论由底向上的非递归版本的归并排序 思想: 对于给定的数组,设置变量sz为每次归并元素的个数。 首先sz为1,也就是每单个元素归并(如:45和23归并成23、45),然后设置sz=sz+sz、也就是2,也就是使得数组中每两个元素归并;依次类推。 图解:  代码: package mergesort; public c...

binbigdata的博客 789

LC148 two-sum

public static int[] twoSum (int[] numbers, int target) { // write code here label: for(int i=0;i<numbers.length-1;i++){ for (int j = i+1; j <numbers.length; j++) { if(target-numbers[j]==numbers[i]){ ..

DemoD_的博客 208

自底向上的归并排序(bottom-up merge sort)

前言 前面已经介绍了归并排序,那是普通的自顶向下的归并排序,下面就让我们来学习自底向上的归并排序。 自底向上的归并排序 1. 首先将数列划分成微小的数列,每个数列也就一到两个元素。 2. 不断合并,2,4,8.。。。 基本排序轨迹图: 来看看c++代码: void merge(int *a, int *aux, int lo, int mid, int hi){ ...

qq_39747794的博客 4973

链表归并排序(递归|非递归)

#include <iostream> #include <vector> #include <stack> using namespace std; struct ListNode { int val; ListNode *next; ListNode () = default; ListNode (int val): ...

vloai 849

leetcode:148. 排序链表(归并排序)

在O(nlogn) 时间复杂度和常数级空间复杂度下,对链表进行排序。 示例 1: 输入: 4->2->1->3 输出: 1->2->3->4 示例 2: 输入: -1->5->3->4->0 输出: -1->0->3->4->5 /* 思路:看到O(n log n) 首先想到的是...

pioneer的博客 634

单向链表的C实现

单向链表: #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct node { struct node*...

WilburYao的博客 254
上一篇: lc 18. 四数之和
下一篇: lc 152. 乘积最大子数组
RedemptionC
博客等级 码龄11年 103粉丝 84原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值