今天改了一下。通过了,但效率排名感人。。代码如下
var targetSlice []int
var incrNum = 0
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
targetSlice = []int{}
incrNum = 0
for {
if l1 == nil && l2 == nil {
if incrNum != 0 {
targetSlice = append([]int{1}, targetSlice...)
}
return sortSliceToList()
}
l1Value := 0
l2Value := 0
if l1 != nil {
l1Value = l1.Val
l1 = l1.Next
}
if l2 != nil {
l2Value = l2.Val
l2 = l2.Next
}
targetValue := l1Value + l2Value
addToTargetSliceNum := 0
targetValue += incrNum
incrNum = 0
if targetValue >= 10 {
addToTargetSliceNum = targetValue % 10
incrNum = targetValue / 10
}else {
addToTargetSliceNum = targetValue
}
targetSlice = append([]int{addToTargetSliceNum}, targetSlice...)
fmt.Println(targetSlice)
}
}
var currentListNode *ListNode = nil
func sortSliceToList() *ListNode {
currentListNode = nil
for _,v := range targetSlice {
currentListNode = &ListNode{Val:v, Next:currentListNode}
}
return currentListNode
}
大概预想到是重复了赋值问题。应该利用回调函数去处理。性能会再提升一点。
现在还没有摆脱问题暴力for的问题。慢慢再做一下。