优秀的程序猿解题之LeetCode 第二题:Add Two Number

Tips:所有代码实现包含三种语言(java、c++、python3)

题目

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。

其中,链表节点的数据结构如下所示:

// java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
// c++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
# python3
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

样例

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

解题

首先看到:

输入:两个链表(l1、l2),分别表示一个非负整数;

输出:一个链表,其满足所表示的非负整数为输入的两个链表所表示的非负整数的和

优秀的程序猿很快理解了问题,然后迅速的把问题转化成计算机好理解的问题:

两个链表逐节点相加,当和大于9时,向下一节点相加进位1

经过一番思考,优秀的程序猿找到了解题规律

分别使用 l1、l2 表示两个链表当前节点,使用 carry_flag 表示上一次节点相加是否发生进位

  1. 如果 l1、l2 均不为空,则计算结果为 l1 + l2 + carry_flag
  2. 如果 l1为空、l2不为空,则计算结果为 l2 + carry_flag
  3. 如果 l2为空、l1不为空,则计算结果为 l1 + carry_flag
  4. 如果 l1、l2 均为空且 carry_flag 为 true,则计算结果为 1
  5. 如果 l1、l2 均为空且 carry_flag 为 false,则计算结束
// java
/*
Runtime: 19 ms, faster than 99.51% of Java online submissions for Add Two Numbers.
Memory Usage: 47.7 MB, less than 45.65% of Java online submissions for Add Two Numbers.
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode head = new ListNode(-1);
    ListNode result = head;
    boolean carry_flag = false;
    while(l1 != null || l2 != null || carry_flag){
        int addition = (l1!=null?l1.val:0) + (l2!=null?l2.val:0) + (carry_flag?1:0);
        carry_flag = addition > 9;
        head.next = new ListNode(addition % 10);
        l1 = l1!=null?l1.next:null;
        l2 = l2!=null?l2.next:null;
        head = head.next;
    }
    return result.next;
}
// c++
/*
Runtime: 40 ms, faster than 96.78% of C++ online submissions for Add Two Numbers.
Memory Usage: 19.2 MB, less than 29.31% of C++ online submissions for Add Two Numbers.
*/
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *head = new ListNode(-1); 
    ListNode *result = head; 
    bool carry_flag = false;
    while(l1 != NULL || l2 != NULL || carry_flag){
        int addition = (l1!=NULL?l1->val:0) + (l2!=NULL?l2->val:0) + (carry_flag?1:0);
        carry_flag = addition>9;
        head->next = new ListNode(addition%10);
        head = head->next;
        l1 = (l1!=NULL?l1->next:NULL);
        l2 = (l2!=NULL?l2->next:NULL);
    }
    return result->next;
}
# Runtime: 108 ms, faster than 67.36% of Python3 online submissions for Add Two Numbers.
# Memory Usage: 13.3 MB, less than 5.21% of Python3 online submissions for Add Two Numbers.
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
    head = ListNode(-1)
    result = head
    carry_flag = 0
    while l1 or  or carry_flag:
        addition = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry_flag
        carry_flag = addition>9
        head.next = ListNode(addition%10)
        head = head.next
        l1 = (l1.next if l1 else None)
        l2 = (l2.next if l2 else None)
    return result.next

Runtime 表现相当不错,但是优秀的程序猿不满足于此,敏锐的直觉告诉优秀的程序猿这个问题还有优化空间。

在上诉解法中,结果链表中每个新节点都是新生成的,Memory Usage相对会大一些,还有一种解题思路是将一个链表加到另一个链表上,然后直接返回这个链表,这样的话,基本上不会构造新节点,可以有效的降低Memory Usage。

具体规则是:

分别使用 l1、l2 表示两个链表当前节点,使用 carry_flag 表示上一次节点相加是否发生进位

  1. 如果 l1、l2 均不为空,则令 l1等于 l1 + l2 + carry_flag
  2. 如果 l1为空、l2不为空,则将 l2 赋给 l1,令 l2 为空
  3. 如果 l1、l2 均为空且 carry_flag 为 true,则令 l1等于 1
  4. 如果 l2 为空且 carry_flag 为 false,则计算结束,返回 l1
// java
/*
Runtime: 19 ms, faster than 99.51% of Java online submissions for Add Two Numbers.
Memory Usage: 41.5 MB, less than 70.58% of Java online submissions for Add Two Numbers.
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode head = new ListNode(-1);
    ListNode result = head;
    head.next = l1;
    boolean carry_flag = false;
    while(l2 != null || carry_flag){
        if(head.next == null && l2 != null){
            head.next = l2;
            l2 = null;
        }else if(head.next == null && carry_flag){
            head.next = new ListNode(1);
            carry_flag = false;
        }else {
            int addition = head.next.val + (l2!=null?l2.val:0) + (carry_flag?1:0);
            carry_flag = addition > 9;
            head.next.val = addition % 10;
            head = head.next;
            l2 = l2!=null?l2.next:null;
        }
    }
    return result.next;
}
/*
Runtime: 36 ms, faster than 99.21% of C++ online submissions for Add Two Numbers.
Memory Usage: 18.7 MB, less than 90.86% of C++ online submissions for Add Two Numbers.
*/
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *head = new ListNode(-1); 
    head->next = l1;
    ListNode *result = head; 
    bool carry_flag = false;
    while(l2 != NULL || carry_flag){
        if(head->next == NULL && l2 != NULL){
            head->next = l2;
            l2 = NULL;
        }else if(head->next == NULL && carry_flag){
            head->next = new ListNode(1);
            carry_flag = false;
        }else{
            int addition = (head->next!=NULL?head->next->val:0) + (l2!=NULL?l2->val:0) + (carry_flag?1:0);
            carry_flag = addition>9;
            head->next->val = addition%10;
            head = head->next;
            l2 = (l2!=NULL?l2->next:NULL);
        }
    }
    return result->next;
}
# python3
# Runtime: 108 ms, faster than 67.36% of Python3 online submissions for Add Two Numbers.
# Memory Usage: 13.3 MB, less than 5.21% of Python3 online submissions for Add Two Numbers.
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
    head = ListNode(-1)
    head.next = l1
    result = head
    carry_flag = 0
    while l2 or carry_flag:
        if not head.next and l2:
            head.next = l2
            l2 = None
        elif not head.next and carry_flag:
            head.next = ListNode(1)
            carry_flag = 0
        else:
            carry_flag, head.next.val = divmod((head.next.val if head.next else 0) + (l2.val if l2 else 0) + carry_flag, 10)
            head = head.next
            l2 = (l2.next if l2 else None)
    return result.next

优秀的程序猿又严谨得审视了几遍代码,满意得合上了电脑。。。

    原文作者:efan
    原文地址: https://www.jianshu.com/p/bd2da561e8c9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞