leetcode(2):Add Two Numbers

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.

Example:

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

題意大致就是給定兩個鏈表按照加法進行運算,因為是鏈表所以最后需要進行一次鏈表的翻轉(zhuǎn)才能得到預(yù)期的結(jié)果這是需要注意的

因為leet限制了數(shù)據(jù)結(jié)構(gòu)并且不希望我們改變他的數(shù)據(jù)結(jié)構(gòu),所以我們不能自定義鏈表的實現(xiàn)只能用他們定義的鏈表實現(xiàn)功能

定義如下

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

這道題并不復(fù)雜來看 一看筆者的初始實現(xiàn)代碼

public class Solution2 {
    ListNode dummyHead = new ListNode(0);

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int mod = 0;
        while (true) {
            int var1 = 0, var2 = 0;
            if (l1 != null) {
                var1 = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                var2 = l2.val;
                l2 = l2.next;
            }
            int sum = var1 + var2 + mod;
            ListNode pre = dummyHead;
            ListNode current = new ListNode(sum % 10);
            current.next = pre.next;
            pre.next = current;
            mod = sum / 10;
            if (l1 == null && l2 == null) {
                break;
            }
        }
        if (mod != 0) {
            ListNode pre = dummyHead;
            ListNode current = new ListNode(mod);
            current.next = pre.next;
            pre.next = current;
        }
        // 反轉(zhuǎn)鏈表
        return reverseList(dummyHead.next);
    }

    public ListNode reverseList(ListNode head) {
        if (head == null)
            return head;
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode pre = head;
        ListNode current = pre.next;
        while (current != null) {
            pre.next = current.next;
            current.next = dummyHead.next;
            dummyHead.next = current;
            current = pre.next;
        }
        return dummyHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}

提交后發(fā)現(xiàn):
Runtime: 2 ms, faster than 100.00% of Java online submissions for Add Two Numbers.
Memory Usage: 46 MB, less than 55.21% of Java online submissions for Add Two Numbers.

從時間復(fù)雜度來說這是一個O(n)復(fù)雜度的度算法,暫無優(yōu)化空間
空間復(fù)雜度相對來說在容忍范圍

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容