題目:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
其實拿到這題的時候,思考的時間還是挺久的,因爲要考慮的情況挺多的,
1>首先處理錯誤輸入
2>然後就是當l1與l2的下面next節點不爲空時怎麼處理
3>那麼當l1,l2有一個next節點爲空時,又怎麼處理,
4>最後進位的維持與最終是否要生成新的節點,
這些都需要考慮進去,第一版代碼相對來說挺長,但很好理解。
/**
* 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) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
int jinwei = 0;
//記錄需要返回的節點
ListNode result = null;
//記錄經運算形成的節點
ListNode node = null;
ListNode temp1 = l1;
ListNode temp2 = l2;
while (temp1 != null && temp2 != null) {
ListNode listNode = null;
int sum = temp1.val + temp2.val + jinwei;
listNode = new ListNode(sum%10);
jinwei = sum/10;
if (node != null) {
node.next = listNode;
} else {
result = listNode;
}
node = listNode;
temp1 = temp1.next;
temp2 = temp2.next;
}
while(temp2 != null ){
int sum = temp2.val + jinwei;
ListNode listNode = new ListNode(sum%10);
jinwei = sum/10;
node.next = listNode;
node = listNode;
temp2 = temp2.next;
}
while(temp1 != null ){
int sum = temp1.val + jinwei;
ListNode listNode = new ListNode(sum%10);
jinwei = sum/10;
node.next = listNode;
node = listNode;
temp1 = temp1.next;
}
if(jinwei == 1){
ListNode listNode = new ListNode(1);
node.next = listNode;
}
return result;
}
相應的Leetcode運行顯示爲:Runtime: 500 ms,Your runtime beats 13.03% of java coders。那麼有沒有有更爲簡潔高效的 代碼呢?(下面這段代碼不是本人的,我看討論區裏較爲簡潔且執行時間較爲快捷的)
/**
* 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) {
int carry =0;
ListNode newHead = new ListNode(0);
ListNode p1 = l1, p2 = l2, p3=newHead;
while(p1 != null || p2 != null){
if(p1 != null){
carry += p1.val;
p1 = p1.next;
}
if(p2 != null){
carry += p2.val;
p2 = p2.next;
}
p3.next = new ListNode(carry%10);
p3 = p3.next;
carry /= 10;
}
if(carry==1)
p3.next=new ListNode(1);
return newHead.next;
}
}
相應的執行時間爲Runtime: 428 ms,Your runtime beats 89.83% of java coders.
其實個人分析而言,感覺第二種解題的方式需要學習,寫出來的代碼簡潔且性能較優,但第一種解法與第二種解法,本人的看法是兩者的執行時間應該基本相同,更確切的說,第一種解法的速度應該較第二種解法更快速,因爲第二種解法的while循環中判斷次數比第一種解法多,在這裏會浪費一點時間,但很微小,因爲這兩種解法的時間複雜度都是一樣的。