My answer
1. 第二遍提交
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode front = null, rear = null;
int sum = 0;
while (true) {
if (l1 == null && l2 == null) {
if (sum == 1) {
rear.next = new ListNode(1);
rear = rear.next;
}
break;
}
// add two numbers
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
// sum is greater than 10
ListNode n = null;
if (sum >= 10) {
n = new ListNode(sum - 10);
sum = 1;
} else {
n = new ListNode(sum);
sum = 0;
}
// LinkedList addRear
if (front == null) {
front = n;
rear = front;
} else {
rear.next = n;
rear = rear.next;
}
}
return front;
}
/**
* 该方法可以写的更优雅:1) 多余的变量 ptr1,ptr2; 2) sum和flag可以合并
*/
public ListNode addTwoNumbers_version0(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode ptr1 = l1, ptr2 = l2;
ListNode front = null, rear = null;
boolean flag = false; // add one to the next bit
int sum = 0;
while (true) {
if (ptr1 == null && ptr2 == null) {
if (flag) {
rear.next = new ListNode(1);
rear = rear.next;
}
break;
}
if (flag) {
sum = 1;
} else {
sum = 0;
}
// add two numbers
if (ptr1 != null) {
sum += ptr1.val;
ptr1 = ptr1.next;
}
if (ptr2 != null) {
sum += ptr2.val;
ptr2 = ptr2.next;
}
// sum is greater than 10
if (sum >= 10) {
sum = sum - 10;
flag = true;
} else {
flag = false;
}
// LinkedList addRear
ListNode n = new ListNode(sum);
if (front == null) {
front = n;
rear = front;
} else {
rear.next = n;
rear = rear.next;
}
}
return front;
}
Summary
1. Keys:
1.1 Two linked lists' lengths are not equal
1.2 Two digit sum (especially the final bit) is more than 10.
1.3 AddRear method of the Linked List
2. 加法运算涉及到进位的问题, thus the digits are stored in reverse order.
3. Submission Details
第一遍提交
尽管绝对的运行时间跟提交那时机器负载有关,但这个图 很有意思!!
1. 大量样本下,程序员的能力呈正态分布。
2. Java语言最慢,C++最快!!
3. 第一遍,我的编程水平(if 大家都是自己做并且一次通过)属于中偏下,代码执行时间还是太慢,值得再优化,打磨。
4. 第二遍提交runtime 提升到了435ms.
本文讨论了如何优化算法来实现链表加法操作,包括改进代码结构、减少冗余变量、合并逻辑判断等步骤,以提高执行效率。通过实例展示了不同提交版本之间的性能对比,最终实现了对进位问题的高效处理。
253

被折叠的 条评论
为什么被折叠?



