【LeetCode】【2】Add Two Numbers
本文最后更新于:2021年12月22日 中午
【主页】系列文章目录
【LeetCode】系列目录
LeetCode系列
Q:You are given two non-empty linked lists representing two nonnegative 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.
1 |
|
E:给定两个非空链表代表两个非负整数,这两个数字被逆序存储并且他们的每一个节点只存一个单一数字,返回这两个数字加起来组合成的新链表。
e.g.
1 |
|
A:
Approach:
因为链表存储顺序刚好和我们做加法的顺序一致,所以我们只需要按照正常数学加法来操作这两个数字即可。
每次拿链表1和链表2的一个元素相加,这个时候可能会有几种情况:
a、链表1和链表2长度不相等,此时取值一个能取,一个已经没有了;
b、链表1和链表2相加,有进位;
c、链表其中一个没有元素,一个还有元素且此时还有进位,需要元素与进位相加;
d、都没有元素,但是此时还有进位。
1 |
|
Complexity Analysis:
- 时间复杂度: O(n)。(LeetCode:64 ms)
- 空间复杂度:O(n)。
联系方式
邮箱: xiebangyao_1994@163.com
相关账号:
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!