1. 程式人生 > >LeetCode系列:2 Add Two Numbers

LeetCode系列:2 Add Two Numbers

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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.


Example:

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

E:給定兩個非空連結串列代表兩個非負整數,這兩個數字被逆序儲存並且他們的每一個節點只存一個單一數字,返回這兩個數字加起來組合成的新連結串列。

你可以假設這兩個數字不是0開頭,除了0它自己

e.g.
輸入:
連結串列1(2 -> 4 -> 3) 連結串列2(5 -> 6 -> 4)
因為342 + 465=807,所以
輸出:
新連結串列:
7
-> 0 -> 8

A:

Approach:

因為連結串列儲存順序剛好和我們做加法的順序一致,所以我們只需要按照正常數學加法來操作這兩個數字即可。
每次拿連結串列1和連結串列2的一個元素相加,這個時候可能會有幾種情況:
a、連結串列1和連結串列2長度不相等,此時取值一個能取,一個已經沒有了;
b、連結串列1和連結串列2相加,有進位;
c、連結串列其中一個沒有元素,一個還有元素且此時還有進位,需要元素與進位相加;
d、都沒有元素,但是此時還有進位。

class Solution {
    func addTwoNumbers(_ l1: ListNode?,
_ l2: ListNode?) -> ListNode? { let header = ListNode(0) var list1 = l1, list2 = l2, carry = 0, tempNode = header while list1 != nil || list2 != nil || carry != 0 {//考慮上面提到的a,b,c,d四種情況 if list1 != nil { carry += list1!.val list1 = list1?.next } if list2 != nil { carry += list2!.val list2 = list2?.next } tempNode.next = ListNode(carry%10) tempNode = tempNode.next! carry /= 10 //獲取進位,如果沒有,則為0 } return header.next//因為一開始例項化的是ListNode(0) ,所以要從下一個開始,不然會多一個0元素 } }
Complexity Analysis:
  • 時間複雜度: O(n)。(LeetCode:64 ms)
  • 空間複雜度:O(n)。