上一篇:1.TwoSum(两数之和)
题目(Medium)
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
给定两个非空链表来代表两个非负数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头
脑洞时间
这个题其实求多位数相加,主要的难点就是进位的记录。还有要注意的有:
1.当两个链表长度不一致时的遍历策略,要注意较长的链表的值相当于原值转移
2.当个链表都遍历相加后依然有进位,eg:13+89=102,存储为[3->1],[9->8],遍历相加后为:[2->0],此时8+1+1(上次进位)又形成了进位,需要新增一位[2->0->1](形成的进位)]
废话少说撸代码
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class LinkList:
def __init__(self):
self.head = None
self.size = 0
def isEmpty(self):
return self.head == None
def length(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.next
return count
def append(self, val):
temp = ListNode(val)
if self.isEmpty():
self.head = temp
else:
current = self.head
while current.next != None:
current = current.next
current.next = temp
def add(self, val):
temp = ListNode(val)
if self.isEmpty():
self.head = temp
else:
temp.next = self.head
self.head = temp
# self.printf()
def printf(self):
if self.isEmpty():
print("NONE")
else:
current = self.head
while current != None:
print(current.val)
current = current.next
class Solution:
# 求当前链表长度
def length(self, l):
current = l
count = 0
while current != None:
count += 1
current = current.next
return count
def addTwoNumbers(self, l1, l2):
rList = LinkList()
if self.length(l1) >= self.length(l2):
current1 = l1
current2 = l2
count = self.length(l2)
else:
current2 = l1
current1 = l2
count = self.length(l1)
zCount = 0
addFlag = 0
while current1 != None:
#按长表来遍历
tempVal = current1.val
# 判断短表是否结束
if zCount < count:
tempVal = tempVal + current2.val
current2 = current2.next
# 判断进位
if addFlag > 0:
tempVal = tempVal + addFlag
addFlag = 0
# 记录进位
if tempVal >= 10:
tempVal = tempVal - 10
addFlag = 1
rList.append(tempVal)
current1 = current1.next
zCount = zCount + 1
# 链表都遍历相加完后依然有进位,新增一位
if addFlag > 0:
rList.append(addFlag)
return rList
def main():
ll1 = LinkList()
ll2 = LinkList()
# 342+465=807
ll1.add(3)
ll1.add(4)
ll1.add(2)
ll2.add(4)
ll2.add(6)
ll2.add(5)
# ll2.add(0)
# l1.printf()
# l2.printf()
l1 = ll1.head
l2 = ll2.head
rl = Solution().addTwoNumbers(l1, l2)
rl.printf()
if __name__ == '__main__':
main()
算法复杂度
时间复杂度为:O(N),N为较长链表的长度,即
空间复杂度为:O(N)
三省吾题
刚开始以为操作的是两个链表,写参数的时候就传了两个链表。Leetcode运行老是报错,说有些方法没有定义。仔细一看,才发现传的参数是节点指针,稍作修改乎就Accepted了。
总结而言,这道题并不难,主要考察数据结构中链表的构造与遍历思路很快就有了,我花费的时间有点长是因为在顺便练习Python的语法。可不要笑话我这个Python新手……
.
.
.
下一篇:3.无重复字符的最长子串(LongestSubstringWithoutRepeatingCharacters)
——————————20180311夜
刷Leetcode,
在我看来,
其实是为了维持一种编程状态!