在leetcode里面学习算法和数据结构,真爽,很好玩。亮点在于,在线提交结果,可以判断自己代码写的好坏,还能看到非常优秀的代码,真是一种享受。学得非常有意思,这里就把自己学习的过程记录下来,以后可以回顾一下。
题目:https://leetcode.com/problems/add-two-numbers/
第一次写的代码:运行速度是58ms,击败了20%的人
分析:代码写得太长了,不够简洁,逻辑比较复杂。
**
* 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 result=l1.val+l2.val;
int tag=0;
if(result>=10)
{
result=result%10;
tag=1;
}
ListNode head=new ListNode(result);
ListNode l=head;
if(l1.next==null&&l2.next==null&&tag==1)
{
l.next=new ListNode(tag);
l=l.next;
}
while(!(l1.next==null&&l2.next==null)){
if(l1.next==null){
result=0+l2.next.val+tag;
l2=l2.next;
}
else if(l2.next==null){
result=l1.next.val+0+tag;
l1=l1.next;
}
else{
result=l1.next.val+l2.next.val+tag;
l1=l1.next;
l2=l2.next;
}
tag=0;
if(result>=10){
tag=1;
result=result%10;
}
l.next=new ListNode(result);
l=l.next;
if(l1.next==null&&l2.next==null&&tag==1)
{
l.next=new ListNode(tag);
l=l.next;
}
}
l.next=null;
return head;
}
}
第二次改进的代码:
分析:代码变得简洁了,逻辑也清晰,代码运行速度提高到33%
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
ListNode head=new ListNode(0);
ListNode current=head;
int index=0;
while(l1!=null||l2!=null){
int x=(l1!=null)?l1.val:0;
int y=(l2!=null)?l2.val:0;
int result=x+y+index;
index=result/10;
current.next=new ListNode(result%10);
current=current.next;
if(l1!=null)l1=l1.next;
if(l2!=null)l2=l2.next;
}
if(index>0){
current.next=new ListNode(index);
}
current.next=null;
return head.next;
}
第三种方法:
分析:运行速度更快,打败了57%的人,特殊情况先处理
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result, node;
int temp, carry = 0;
if (l1 == null && l2 == null) {
return null;
}
result = new ListNode(0);
node = result;
do {
temp = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
carry = temp < 10 ? 0 : 1;
node.next = new ListNode(temp % 10);
node = node.next;
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
} while (l1 != null || l2 != null || carry > 0);
return result.next;
}