leetCode笔记(一)

题目:

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

image

开始想的简单啊,把链表转换成整数,两个整数相加,再转换成链表。
'''
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var tempL1 = l1;
var tempL2 = l2
var i=1;
var num1=0;
var num2 = 0
while (tempL1 != nil) {
num1=num1 + i(tempL1?.val)!
i=i
10
tempL1=tempL1?.next
}
i=1
while (tempL2 != nil) {
num2=num2 + i(tempL2?.val)!
i=i
10
tempL2=tempL2?.next
}
var resNum = num1+num2

    print("resnum: "+String( resNum))
    var res = ListNode.init(0);
    var restemp=res
    print("resnumII: "+String( i))
    while (Int(resNum/10)) != 0 {
        restemp.val=Int(resNum%10)
        print(restemp.val)
        restemp.next=ListNode.init(0)
        restemp=restemp.next!
        resNum=resNum/10
    }
    restemp.val = resNum
    print(resNum)
    return res
}

func generListByArr(_ nums: [Int]) -> ListNode {
    var i=0;
    var res=ListNode.init(0)
    var restemp=res
    while i

'''

后来然后运行示例,完美。提交以后发现在数据很大时候,内存溢出。


image.png

重新理下思路,没那么复杂,其实就是小学加减法用链表表达一下
'''
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var tempL1 = l1;
var tempL2 = l2
var upStack=0
var tempRes:ListNode?=ListNode.init(0)
let res=tempRes

    while ( (tempL1?.next != nil) || tempL2?.next != nil ) {
      
        if tempL1?.next==nil{
            tempL1?.next=ListNode.init(0)
        }
        if tempL2?.next==nil{
            tempL2?.next=ListNode.init(0)
        }
        if tempRes?.next==nil{
        tempRes?.next=ListNode.init(0)
        }
    tempRes!.val = (upStack+tempL1!.val+tempL2!.val)%10
        print(tempRes!.val )
        upStack=(upStack+tempL1!.val+tempL2!.val)/10
        
        tempRes = tempRes?.next
        tempL1=tempL1?.next
        tempL2=tempL2?.next
       
        
        
    }
    tempRes!.val = (upStack+tempL1!.val+tempL2!.val)%10
    print(tempRes!.val )
    upStack=(upStack+tempL1!.val+tempL2!.val)/10
    
    if upStack>0 {
        tempRes?.next=ListNode.init(1)
        print(1)
    }

 
    return res
}

'''

思路简单,代码调试起来太费神了。

你可能感兴趣的:(leetCode笔记(一))