02 Add Two Numbers

https://leetcode.com/problems/add-two-numbers/?tab=Description

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

代码 && 分析

自己的做法,从头走一遍,不在原链表操作,每次移动都创建一个新节点。

使用while(l1 != null && l2 != null).

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode dummy = new ListNode(-1);
        ListNode head = dummy;
        int carry = 0;
        while (l1 != null && l2 != null) {
            int currentVal = l1.val + l2.val + carry;
            head.next = new ListNode(currentVal % 10);
            carry = currentVal / 10;
            head = head.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            int currentVal = l1.val + carry;
            head.next = new ListNode(currentVal % 10);
            carry = currentVal / 10;
            head = head.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            int currentVal = l2.val + carry;
            head.next = new ListNode(currentVal % 10);
            carry = currentVal / 10;
            head = head.next;
            l2 = l2.next;
        }
        if (carry == 1) {
            head.next = new ListNode(1);
        }
        return dummy.next;
    }

但是看了答案,觉得使用&&判断代码看着比较冗余,可以使用||

代码如下:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null) {
            return l2;
        }
        if(l2 == null) {
            return l1;
        }
        ListNode dummy = new ListNode(-1);
        ListNode current = dummy;
        int carry = 0;
        while(l1 != null || l2 != null) {
            int currentSum = carry;
            if(l1 != null) {
                currentSum += l1.val;
                l1 = l1.next;
            }
            if(l2 != null) {
                currentSum += l2.val;
                l2 = l2.next;
            }
            carry = currentSum / 10;
            current.next = new ListNode(currentSum % 10);
            current = current.next;
        }
        if(carry == 1) {
            current.next = new ListNode(1);
        }
        return dummy.next;
    }

同理,对于什么合并array之类的操作也可以用相同的方式。

时间复杂度是O(n)

results matching ""

    No results matching ""