时间复杂度分析:遍历次数等于位数较多的那个数,因此时间复杂度位 O(max(n, m))
解题思路:该解法中先同时遍历两个数,直到某一个数的位数用尽了。然后另起循环,遍历另一个数的剩余位,计算它们与进位相加后的结果。这样可以减少一些不必要的运算。另外在第二次遍历时,一旦在某位上进位终止了,即进位为0,而不是1时,则剩余的没有遍历的必要了,直接将剩余部分续接到结果链表末尾即可。
package com.happy.leetcode.p2; import com.happy.leetcode.util.ListNode; /** * 64.08% * @author bird * */ public class AddTwoNumbersV2 { public static void main(String[] args) { int[] n1 = {8, 6}; int[] n2 = {6, 4, 8}; AddTwoNumbersV2 ins = new AddTwoNumbersV2(); ListNode l1 = ins.generateNodeByArray(n1); ListNode l2 = ins.generateNodeByArray(n2); ins.printListNode(l1); ins.printListNode(l2); ins.printListNode(ins.addTwoNumbers(l1, l2)); } private ListNode generateNodeByArray(int[] nums) { ListNode result = new ListNode(nums[nums.length-1]); ListNode tmp; for(int i=nums.length-2; i>=0; i--) { tmp = result; result = new ListNode(nums[i]); result.next = tmp; } return result; } private void printListNode(ListNode listNode) { while(listNode!=null) { System.out.print(listNode.val+" "); listNode = listNode.next; } System.out.println(); } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1==null && l2==null) { return null; } if(l1==null) { return l2; } if(l2==null) { return l1; } int bitResult = l1.val+l2.val; int carry = 0; ListNode result = new ListNode(bitResult); if(bitResult>=10) { carry = 1; result = new ListNode(bitResult-10); } ListNode last = result; ListNode next = null; l1 = l1.next; l2 = l2.next; while(l1!=null && l2!=null) { bitResult = l1.val+l2.val+carry; if(bitResult>=10) { carry = 1; next = new ListNode(bitResult-10); }else { carry = 0; next = new ListNode(bitResult); } last.next = next; last = next; l1 = l1.next; l2 = l2.next; } while(l1!=null) { if(carry==0) { last.next = l1; break; } bitResult = l1.val+carry; l1 = l1.next; if(bitResult>=10) { carry = 1; next = new ListNode(bitResult-10); }else { carry = 0; next = new ListNode(bitResult); } last.next = next; last = next; } while(l2!=null) { if(carry==0) { last.next = l2; break; } bitResult = l2.val+carry; l2 = l2.next; if(bitResult>=10) { carry = 1; next = new ListNode(bitResult-10); }else { carry = 0; next = new ListNode(bitResult); } last.next = next; last = next; } if(carry>0) { next = new ListNode(carry); last.next = next; } return result; } } 时间复杂度分析:时间复杂度同上,为 O(max(n, m))