LeetCode第[2]题(Java):Add Two Numbers (链表相加)——Medium
题目难度:Medium
题目:
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 two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
翻译:
给出两个非空链表,表示两个非负整数。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字值相加并将其作为此类链表返回。
您可以假设这两个数字不是任何0开头的数字,除了数字0本身。
示例:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 【就是342加上465】
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
我的思路:因为要层层向下直到某一个节点的后继为空,所以想到用while循环,中间有考虑使用递归,但是发现不可以,
因为使用递归有两点要求:1、最内层能不依赖其他层的计算值单独计算,并且能返回一个值帮助其他层得出结果;
2、最外层到最内层都能层级向下表示下一层。
而本题中是LinkedList 而且是单链表,所以只有一个方向,所以由要求2可以得出,第一位(个位)既是最外层,那么问题来了,最内层(最高位)并不能自己计算而返回其他层需要的数,
相反“最外层”却可以,所以互相矛盾,不能使用递归。
明显while后面的条件应该是l1与l2任何一个不为空,
循环体内——做加法,得到值存入一个ListNode,再将这个node引用传给指针pointer的后继【pointer,作为移动的指针存储每一个值,再取自己后继传给自己】,
l1与l2取自己的后继,后续优化加上仅剩一个加数的情况(一个后续为空,进位为0)判断。代码如下:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int c = 0;
ListNode start = new ListNode(0); // 需要一个头结点,不然无法在第一个进行选连接
ListNode pre = start; // 需要一个前置移动节点,对每一个环节进行选择
start.next = l1;
while (l1 != null || l2 != null) {
int temp1 = 0; // 默认为0
int temp2 = 0;
if (l1 == null) {
pre.next = l2;
if (c == 0) {
return start.next; // l1为空,进位为0,后面直接就是l2
}
} else {
temp1 = l1.val; // 不为空才提取节点的值。
l1 = l1.next;
} if (l2 == null && c==0) {
return start.next; // l2为空,进位为0,后面直接就是l1
} else if (l2 != null) {
temp2 = l2.val;
l2 = l2.next;
} pre.next.val = (temp1 + temp2 + c) % 10;
c = (temp1 + temp2 + c) / 10;
pre = pre.next;
} if (c > 0) {
pre.next = new ListNode(1);
}
return start.next;
}
1562 / 1562 test cases passed. Status: Accepted Runtime: 53 ms beats 70.37%
编写过程出现的问题:
1、在计算sum时用if else的思想去使用了三目运算符,导致长且难看。三目运算符应该用就地取值的思想,尽量不要嵌套使用。
2、纠结了很久是不是该用一个ListNode来做指针。对于List中节点计算,一般都需要两个node来记录结果,一个记录最开始的位置(head),一个作为指针做计算。
3、没有判断最后只剩进位的情况。当做条件判断和条件循环的时候,一定要考虑出判断和循环后是否还有什么情况是需要计算的,此题出了循环后就是l1与l2都为null,此时还有可能有进位!,所以还需要加上。
下面是参考答案:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
1562 / 1562 test cases passed. Status: Accepted Runtime: 63 ms beats 33.34%
和我的思路几乎一致,并且我的算法中加入了“仅剩一个加数”的情况判断,所以性能上更优~
阿哈哈哈哈,本王终于靠自己的不世才华战胜了参考答案!
元宵快乐哈~~(苦逼的我初八就到学校来了,ค(TㅅT)………)~~
LeetCode第[2]题(Java):Add Two Numbers (链表相加)——Medium的更多相关文章
- LeetCode第四题,Add Two Numbers
题目原文: You are given two linked lists representing two non-negative numbers. The digits are stored in ...
- 【LeetCode每天一题】Add Two Numbers(两链表相加)
You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...
- [LeetCode]2. Add Two Numbers链表相加
注意进位的处理和节点为null的处理 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int flag = 0; ListNode ...
- LeetCode第[18]题(Java):4Sum 标签:Array
题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...
- LeetCode第[1]题(Java):Two Sum 标签:Array
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2
题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...
- LeetCode第[66]题(Java):Plus One
题目:数组加一 难度:Easy 题目内容: Given a non-empty array of digits representing a non-negative integer, plus ...
- 【LeetCode刷题系列 - 002题】Add Two Numbers
题目: You are given two non-empty linked lists representing two non-negative integers. The digits are ...
随机推荐
- C# 利用StringBuilder提升字符串拼接性能
一个项目中有数据图表呈现,数据量稍大时显得很慢. 用Stopwatch分段监控了一下,发现耗时最多的函数是SaveToExcel 此函数中遍列所有数据行,通过Replace替换标签生成Excel行,然 ...
- 【Python之路】第十八篇--MySQL(一)
一.概述 1.什么是数据库 ? 答:数据的仓库. 2.什么是 MySQL.Oracle.SQLite.Access.MS SQL Server等 ? 答:他们均是一个软件,都有两个主要的功能: a. ...
- ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry ’1′ for key
当我用SQLyog尝试修改已有记录的mysql数据表的主键为自动增长时,报出以下错误 ALTER TABLE causes auto_increment resequencing, resulting ...
- T-SQL with关键字 with as 递归循环表
)SET @OrgId = N'901205CA-6C22-4EE7-AE4B-96CC7165D07F'; WITH Childs AS ( SELECT * FROM HROrgRelation ...
- 在容器最前面添加DOM元素 parent.insertBefore(new, parent.children[0])
//判断容器当前有没有子级元素,如果没有直接appendChild就行了; if (p.children[0]) { p.insertBefore(span, p.children[0]); } el ...
- Django HttpRequest对象详解
WSGIRequest对象 Django在接收到http请求之后,会根据http请求携带的参数以及报文信息创建一个WSGIRequest对象,并且作为视图函数第一个参数传给视图函数.也就是我们经常看到 ...
- EXP直接导出压缩问津,IMP直接导入压缩文件的方法
在10G之前,甚至在10G的Oracle环境中,有很多数据量不大,重要性不太高的系统依然采用EXP/IMP逻辑导出备份方式,或者,作为辅助备份方式. 通常情况下,我们都是这样操作的:1.exp导出2. ...
- 0501-Hystrix保护应用-超时机制、断路器模式简介
一.概述 hystrix对应的中文名字是“豪猪”,豪猪周身长满了刺,能保护自己不受天敌的伤害,代表了一种防御机制,这与hystrix本身的功能不谋而合,因此Netflix团队将该框架命名为Hystri ...
- Android图片加载框架Picasso最全使用教程4
通过前几篇的学习,我们已经对Picasso的加载图片的用法有了很深的了解,接下来我们开始分析Picasso为我们提供的其他高级功能及内存分析,Let’sGo ! Picasso进行图片的旋转(Rota ...
- Centos学习笔记2-网络部分
一:修改IP地址:vi /etc/sysconfig/network-scripts/ifcfg-eth0 IPADDR=192.168.80.100 NETMASK=255.255.255.0 GA ...