标签:ons 复杂 etc next node 题解 else 循环 tco
https://leetcode-cn.com/problems/add-two-numbers/submissions/
我的方法:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 ListNode ans = new ListNode(0); 12 ans.next = null; 13 ListNode curr = ans; 14 15 int c = 0; 16 while(l1.next != null && l2.next != null){ 17 curr.val = (l1.val + l2.val + c)%10; 18 c = (l1.val + l2.val + c)/10; 19 curr.next = new ListNode(0); 20 curr = curr.next; 21 l1 = l1.next; 22 l2 = l2.next; 23 } 24 //两数等长度时同时处理最后一个数即可 25 if(l1.next == null && l2.next == null){ 26 curr.val = (l1.val + l2.val + c)%10; 27 c = (l1.val + l2.val +c)/10; 28 //看最终是否还有一位进位 29 if(c == 1){ 30 curr.next = new ListNode(c); 31 curr.next.next = null; 32 }else{ 33 curr.next = null; 34 } 35 return ans; 36 } 37 //一长一短时,留下长的那个,把短的的最后一个val记录后用不着了 38 ListNode l; 39 if(l1.next != null && l2.next == null){ 40 l = l1; 41 curr.val = l2.val; 42 }else{ 43 l = l2; 44 curr.val = l1.val; 45 } 46 //处理短的的最后一位 47 curr.val += l.val + c; 48 c = curr.val / 10; 49 curr.val %= 10; 50 curr.next = new ListNode(0); 51 curr = curr.next; 52 l = l.next; 53 54 while(l.next != null){ 55 curr.val = (l.val + c)%10; 56 c = (l.val + c)/10; 57 curr.next = new ListNode(0); 58 curr = curr.next; 59 l = l.next; 60 } 61 62 //处理长的的最后一位 63 curr.val = (l.val + c)%10; 64 c = (l.val + c)/10; 65 if(c == 1){ 66 curr.next = new ListNode(c); 67 curr.next.next = null; 68 }else{ 69 curr.next = null; 70 } 71 72 return ans; 73 } 74 }
按部就班的考虑与处理.注意不要有考察漏掉的情况
时间复杂度O(n),空间复杂度O(n)
//我所有的时空复杂度都是指级别,有必要具体分析的会特别注明
结果:
官方题解方法:
https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode/
也是朴素方法,区别在于他没有拆开来考虑,而是用了或判断,在末尾前进的时候又加了if
代码量比我的少,优雅一些.
(见仁见智,我不喜欢在简单的循环里加判断,徒增复杂度)
标签:ons 复杂 etc next node 题解 else 循环 tco
原文地址:https://www.cnblogs.com/IsuxizWorld/p/11219194.html