【Leetcode】445. Add Two Numbers II

来源:互联网 发布:php编程第3版pdf 编辑:程序博客网 时间:2024/06/05 07:16

445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

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

题目大意:


给定两个链表,两个链表代表的是两个整数,按照整数加法的方式将两个链表的值相加。

解题思路:

思路一:涉及到进位的问题,因为不能把链表翻转。尝试使用递归的方式来解决这个问题。将两个链的值相加,最终确定的值需要与下一位传回的进位(1/0)才能确定。如果最后最高位进一位,就创建一个新的节点存储进位值。

时间复杂度O(max(M,N))

缺点:由递归本身特性决定的算法的速率不佳。


思路二:创建一个数组存储两个链表的加和,最后把加和写回链表。

时间复杂度O(max(M,N))

空间复杂度O(max(M,N))

优点:由于放弃使用递归,算法的速率应该有提升。



代码:

思路一代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode aPointer,head;
        int length1=0,length2=0;
        int backup;
        
        aPointer = l1;
        while(aPointer!=null){
            aPointer = aPointer.next;
            length1++;
        }
        aPointer = l2;
        while(aPointer != null){
            aPointer = aPointer.next;
            length2++;
        }
        
        if(length1 == 0){
            return l2;
        }else if(length2 ==0){
            return l1;
        }
        
        
        
        if(length1>length2){
            head = l1;
        }else{
            head = l2;
            l2 = l1;
            l1 = head;
        }
        backup = l1.val;
        int res = formerSum(l1,l2,Math.abs(length1-length2));
        if(res == 1){
            ListNode aNode = new ListNode(1);
            aNode.next = l1;
            //aNode.val =1;
            return aNode;
        }else{
            return l1;
        }
    }
    
    public int formerSum(ListNode l1,ListNode l2,int dis){ 
        if(dis == 0){
            if(l1.next != null){
                l1.val += formerSum(l1.next,l2.next,0)+l2.val;
            }else{
                l1.val += l2.val;
            }
            if(l1.val >= 10){
                l1.val -= 10;
                return 1;
            }else{
                return 0;
            }
        }else{
            l1.val += formerSum(l1.next,l2,dis-1);
            if(l1.val >= 10){
                l1.val -= 10;
                return 1;
            }else{
                return 0;
            }
        }
    }
}


思路一结果:


0 0
原创粉丝点击