LeetCode2_Add Two Numbers

LeetCode --- 2. Add Two Numbers 解题报告 2. Add Two Numbers 解题报告 阅读详情
My answer

1. 第二遍提交

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode front = null, rear = null;
        int sum = 0;
        while (true) {
            if (l1 == null && l2 == null) {
                if (sum == 1) {
                    rear.next = new ListNode(1);
                    rear = rear.next;
                }
                break;
            }

            // add two numbers
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }

            // sum is greater than 10
            ListNode n = null;
            if (sum >= 10) {
                n = new ListNode(sum - 10);
                sum = 1;
            } else {
                n = new ListNode(sum);
                sum = 0;
            }

            // LinkedList addRear
            if (front == null) {
                front = n;
                rear = front;
            } else {
                rear.next = n;
                rear = rear.next;
            }
        }

        return front;
    }


2. 第一遍提交

    /**
     * 该方法可以写的更优雅:1) 多余的变量 ptr1,ptr2; 2) sum和flag可以合并
     */
    public ListNode addTwoNumbers_version0(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode ptr1 = l1, ptr2 = l2;
        ListNode front = null, rear = null;
        boolean flag = false; // add one to the next bit
        int sum = 0;
        while (true) {
            if (ptr1 == null && ptr2 == null) {
                if (flag) {
                    rear.next = new ListNode(1);
                    rear = rear.next;
                }
                break;
            }

            if (flag) {
                sum = 1;
            } else {
                sum = 0;
            }

            // add two numbers
            if (ptr1 != null) {
                sum += ptr1.val;
                ptr1 = ptr1.next;
            }
            if (ptr2 != null) {
                sum += ptr2.val;
                ptr2 = ptr2.next;
            }

            // sum is greater than 10
            if (sum >= 10) {
                sum = sum - 10;
                flag = true;
            } else {
                flag = false;
            }

            // LinkedList addRear
            ListNode n = new ListNode(sum);
            if (front == null) {
                front = n;
                rear = front;
            } else {
                rear.next = n;
                rear = rear.next;
            }
        }

        return front;
    }

Summary

 1. Keys: 

        1.1  Two linked lists' lengths are not equal

        1.2  Two digit sum (especially the final bit) is more than 10.

        1.3  AddRear method of the Linked List

2. 加法运算涉及到进位的问题, thus the digits are stored in reverse order. 

3.  Submission Details

      第一遍提交



尽管绝对的运行时间跟提交那时机器负载有关,但这个图 很有意思!!

1.     大量样本下,程序员的能力呈正态分布。

2.     Java语言最慢,C++最快!!

3.    第一遍,我的编程水平(if 大家都是自己做并且一次通过)属于中偏下,代码执行时间还是太慢,值得再优化,打磨。

4.    第二遍提交runtime 提升到了435ms.     

[LeetCode]--2. Add Two Numbers You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linke 阅读详情

相关推荐

使用Kettle进行数据同步(增量)

文章目录kettle介绍kettle安装kettle使用使用kettle同步关系型数据库数据(MySQL示例)1. 创建一个转换2. 选择表输入3. 格式转换4. 执行脚本5. 创建job使用kettle同步NoSql数据(MongoDB示例)创建转换时的注意事项MongoDBInput怎么创建job的创建如何在Linux上面运行已经创建好的job?1、把创建好的job传输到Linux机器上面2、编辑kjb文件3、执行任务 kettle介绍 Kettle 是一款国外开源的 ETL 工具,纯 Java 编写

JenKin的博客 7351

leetcode: Add Two Numbers

题目: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the ...

时梦的博客 259

Multisim仿真入门:单相半波可控整流电路从搭建到波形分析(附避坑指南)

本文为电力电子技术初学者提供了一份详细的Multisim仿真指南,手把手教你从零搭建单相半波可控整流电路。通过对比纯电阻、阻感负载及加入续流二极管后的波形变化,直观理解晶闸管触发、电感续流等核心原理,并附有实用的参数设置与常见问题避坑指南,帮助你将抽象理论转化为可视化的工程实践。

weixin_29208077的博客 343

LeetCode 2. Add Two Numbers(C++)

使用了O(1)的额外空间,思路是将两个链表遍历并合并,合并过程中不断计算进位,如果计算到最后一次加法仍有进位(可能是两个链表对应位置值相加产生进位或者上一次的进位加本次值又产生进位),那么需要加一个值为1的新结点。 这种思路的优点是空间复杂度小,缺点是实现比较复杂(跟借助一个额外的数组和链表相比)。 /** * Definition for singly-linked list. * st

赞美月亮的专栏 1435

别再羡慕专业版!用这个批处理脚本,一键给Win11家庭版装上官方沙盒

本文详细介绍了如何通过批处理脚本在Windows 11家庭版上安装官方Windows沙盒(Windows Sandbox),无需复杂操作即可享受专业版功能。脚本自动激活系统内置组件,提供安全隔离的虚拟化环境,适用于软件测试、安全浏览等场景。

weixin_26757925的博客 491

python爬虫案例——腾讯网新闻标题(异步加载网站数据抓取,post请求)(6)

本篇案例主要讲解异步加载网站如何分析网页接口,以及如何观察post请求URL的参数,网站数据并不难抓取,主要是将要抓取的数据接口分析清楚,才能根据需求编写想要的代码。

@优快云盲敲代码的阿豪的博客 945

Leetcode 2 Add Two Numbers

Leetcode 2 Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add t...

博学 笃志 切问 近思 197

基于 YOLOv8 的自动驾驶车辆障碍物检测与避障路径规划

本文探讨基于YOLOv8的自动驾驶车辆障碍物检测与避障路径规划系统。在感知层面,采用YOLOv8模型实现多类别障碍物识别,结合单目视觉距离估计和ByteTrack多目标跟踪算法,完成障碍物的稳定检测与运动状态估计。在路径规划层面,设计分层规划架构,融合全局路径规划与局部避障算法,重点实现Frenet坐标系下的采样优化算法和基于模型预测控制的实时避障轨迹生成。通过完整的代码实现与仿真实验,验证系统在复杂交通场景下的有效性与实时性,为自动驾驶开发者提供从理论到实践的完整技术参考。 关键词:YOLOv8;自动驾驶

huanghm88的专栏 248

LeetCode 2.Add Two Numbers 两数相加 Python3 三种解法

LeetCode 2.Add Two Numbers 两数相加 Python3 由于做提前连链表是怎么实现的都不知道所以补了点课。 Single Linked List 代码来自这位兄台 pasilo https://blog.51cto.com/13047263/2070815 内容理解我看的知乎 如何更好的理解链表 以下代码和LeetCode上面的链表稍微有些许不同,那个里面链表和链表上面的节...

Aixoum is Me 1290

WorkBuddy 技能指南:基础办公与文档处理

WorkBuddy 不仅仅是一个对话工具——它通过技能(Skills)系统,将通用 AI 助手转变为具备专业领域能力的智能助手。每个技能都是一套经过精心设计的"能力包",包含专业知识、工作流程和专用工具。本文聚焦于文档处理类技能——这是日常工作中使用频率最高、最实用的能力集合。

u011186532的专栏 703

安卓中蓝牙免提HFP的一些分析

最近看了一些大牛的博客,无不提到了技术分享的重要性,的确,分享自己的知识不仅仅是与他人讨论并相互提高的过程,更是对自己知识的梳理。希望自己能以此为契机,形成周期性博客分享的习惯。 文章标题为HFP的一些分析,HFP(Hand Free Profile)主要定义了安卓中与接打电话相关的一些功能的实现。本文主要介绍这其中对于HFP非常重要的Service Level Connection的建立。首先...

底层码农 771

leetcode 21. Merge Two Sorted Lists和2. Add Two Numbers

【代码】leetcode 21. Merge Two Sorted Lists和2. Add Two Numbers。

weixin_41554427的博客 442

【即插即用模块】注意力篇 | TIP 2024 | 注意力机制的有效改进!内容引导注意力块CGA,空间-通道-像素三个维度融合,实现涨点!

CGA(Content-Guided Attention)是一种融合多维度注意力的即插即用模块,通过并联空间和通道注意力并与像素注意力串联,实现从通道、空间到像素的三层级特征筛选。该模块采用层级递进设计,解决了传统单维度注意力的局限性,尤其适用于图像恢复等对特征精度要求高的任务。实验表明,CGA在去雾任务中能显著提升指标,但会略微增加参数量。模块代码支持灵活集成到各类视觉模型中,建议放置在网络靠前位置以充分释放后续层性能。其核心创新在于通过7×7大卷积捕捉长距离依赖,结合分组卷积实现像素级细粒度建模

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 226

LeetCode-2. Add Two Numbers

刚刚我经历了可能是2017年3月22号的最大的大起大落。

public Blog myBlog(){ 1125

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

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

[leetcode] 2. Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a link

TstsUgeg的博客 405

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

[LeetCode] 2. Add Two Numbers

2. Add Two Numbers 反序求和 链表操作

ZY的博客 301

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Leetcode[2] Add Two Numbers and Leetcode[445] Add Two Numbers II

Leetcode[2] Add Two Numbers class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ...

只为分享 252

力扣Leetcode 2 两数相加 Add Two Numbers

暴力法 递归法

qq_39674417的博客 177

【Java版】LeetCode 力扣第 2 题:两数相加 (Add Two Numbers)

题目描述 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 You are given two non-empty l

代码时光 752

Leetcode学习笔记:#2 Add Two Numbers

Leetcode学习笔记:#2 Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. ...

ccystewart的博客 167

【LeetCode】2. Add Two Numbers 解题报告(Python)

【LeetCode】2. Add Two Numbers 解题报告(Python)题目描述解法一:先求和,再构建链表解法二:采用一个进位carry方便的完成一次遍历得出结果解法三:递归 题目地址:https://leetcode.com/problems/add-two-numbers/ 题目描述 You are given two non-empty linked lists represent...

ttinch的博客 261

LeetCode 2. Add Two Numbers - 链表(Linked List)系列题1

题目大意:用两个非空链表来表示两个非负整数,链表的一个节点表示数字的其中一位,数字在链表中是以反顺序存储的,即最低位在前最高位在后。要求相加两个数把和存到一个新链表中。

hgq522的博客 380

[leetcode2] Add Two Numbers

[leetcode2]Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add t

Cathy1994的专栏 464

Leetcode 2. Add Two Numbers

题目链接:2. Add Two Numbers 题目大意:给你由两个链表组成得数,链表上得每个位置得值代表一个位得值,例如3->8->4就代表483这个值,然后两个链表相加,返回结果。 题目思路:简单题,每次相加得时候记录一次进位就可以了,只不过处理链表得时候比较麻烦,具体看代码 时间复杂度&&空间复杂度:O(max(n,m))&&O(n+m)(n,m分...

Nemaleswang的博客 306
上一篇: win7安装virtualbox遇到的问题
下一篇: LeetCode1_Two Sum
cuidiwhere
博客等级 码龄19年 133粉丝 102原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值