LeetCode---两数相加2

本文最后更新于:2021年8月8日 下午

LeetCode—两数相加2

给你两个非空的链表,表示两个非负的整数。他们每位数字都是按照逆序的方式存储的,,并且每个节点只能存储一位数字。

请你将两数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字0之外,这两个数都不会以0开头


例如:

输入:2–4–3

​ 5–6–4

输出:7–0–8


解法:

1、迭代法

class Solution {
    // Iteration
    // N is the size of l1, M is the size of l2
    // Time Complexity: O(max(M,N))
    // Space Complexity: O(max(M,N)) if dummy is counted else O(1)
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int next1 = 0;
        int total = 0;
        ListNode dummy = new ListNode();
        ListNode cur = dummy;
        while (l1 != null && l2 != null) {
            total = l1.val + l2.val + next1;
            cur.next = new ListNode(total % 10);
            next1 = total / 10;
            l1 = l1.next;
            l2 = l2.next;
            cur = cur.next;
        }

        while (l1 != null) {
            total = l1.val + next1;
            cur.next = new ListNode(total % 10);
            next1 = total / 10;
            l1 = l1.next;
            cur = cur.next;
        }

        while (l2 != null) {
            total = l2.val + next1;
            cur.next = new ListNode(total % 10);
            next1 = total / 10;
            l2 = l2.next;
            cur = cur.next;
        }

        if (next1 != 0) {
            cur.next = new ListNode(next1);
        }

        return dummy.next;
    }
}

2、递归法

class Solution {
    // Recursion
    // N is the size of l1, M is the size of l2
    // Time Complexity: O(max(M,N))
    // Space Complexity: O(max(M,N)) if dummy is counted else O(1)
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int total = l1.val + l2.val;
        int next1 = total / 10;
        ListNode res = new ListNode(total%10);
        if (l1.next != null || l2.next != null || next1 != 0) {
            l1 = l1.next!=null ? l1.next : new ListNode(0);
            l2 = l2.next!=null ? l2.next : new ListNode(0);
            l1.val += next1;
            res.next = addTwoNumbers(l1, l2);
        }
        return res;
    }
}

另外写一下递归与迭代的区别:

递归和迭代都是循环中的一种。

简单地说,递归是重复调用函数自身实现循环。迭代是函数内某段代码实现循环,而迭代与普通循环的区别是:循环代码中参与运算的变量同时是保存结果的变量,当前保存的结果作为下一次循环计算的初始值。

递归循环中,遇到满足终止条件的情况时逐层返回来结束。迭代则使用计数器结束循环。当然很多情况都是多种循环混合采用,这要根据具体需求。

使用递归要注意的有两点:

1)递归就是在过程或函数里面调用自身;
2)在使用递归时,必须有一个明确的递归结束条件,称为递归出口.

递归分为两个阶段:

1)递推:把复杂的问题的求解推到比原问题简单一些的问题的求解;
2)回归:当获得最简单的情况后,逐步返回,依次得到复杂的解.

递归和迭代的空间利用率

迭代是逐渐逼近,用新值覆盖旧值,直到满足条件后结束,不保存中间值,空间利用率高。
递归是将一个问题分解为若干相对小一点的问题,遇到递归出口再原路返回,因此必须保存相关的中间值,这些中间值压入栈保存,问题规模较大时会占用大量内存。