Leetcode題目訓練日記(Java實現):#2. Add Two Numbers
阿新 • • 發佈:2018-12-19
一、題目
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.
二、本人答案,Runtime:29ms
//Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode p=l1; ListNode q=l2; int jinwei=0; while (p!=null&&q!=null){ int tmp; if (jinwei==1){ tmp=p.val+q.val+1; }else { tmp = p.val + q.val; } if(tmp>9){ jinwei=1; tmp%=10; }else { jinwei=0; } p.val=tmp; q.val=tmp; //當p,q等長時,為了避免丟失l1,l2中最後一個非空節點的指標, //從而導致因進位而new的新節點,無法正確連線到l1或l2末尾 if(p.next==null&&q.next==null){ if (jinwei==1){ p.next=new ListNode(1); } return l1; } p=p.next; q=q.next; } //下面的程式碼是在說:p,q誰長處理誰,並最終用其做返回 if(p!=null){ while (jinwei==1){ p.val+=1; if(p.val>9){ if(p.next==null){ p.next=new ListNode(1); jinwei=0; } p.val%=10; p=p.next; }else { jinwei=0; } } return l1; } if (q!=null){ while (jinwei==1){ q.val+=1; if(q.val>9){ if(q.next==null){ q.next=new ListNode(1); jinwei=0; } q.val%=10; q=q.next; }else { jinwei=0; } } return l2; } return null; } }
程式碼看起來有點長,囉裡囉嗦的,但實際思路很簡單:從個位開始,將兩條連結串列上的數相加結果存放在做相加的兩個節點中去,最終返回較長的那個連結串列(兩個連結串列等長時隨意返回一條)。 這裡最複雜的問題就是處理進位問題,例如:1+9999,在第一個while結束之後,還要利用迴圈依次進位,並在最後new一個新節點存放最後的進位;5+5,要在p,q變為null之前,new新節點,並連線到l1末尾。 時間複雜度:O(n),空間複雜度:O(1)
三、優秀答案,Runtime:23ms
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); int carry = 0; while(l1!=null||l2!=null||carry>0) { ListNode itr = head; while(itr.next!=null) itr = itr.next; int sum = ( (l1==null ? 0 : l1.val) + (l2==null ? 0 : l2.val) + carry); carry = sum/10; ListNode temp = new ListNode(sum%10); itr.next = temp; if(l1!=null) l1 = l1.next; if(l2!=null) l2 = l2.next; } return head.next; } }