2021-11-01 每日打卡:腾讯精选50题
写在前面
“这些事儿在熟练之后,也许就像喝口水一样平淡,但却能给初学者带来巨大的快乐,我一直觉得,能否始终保持如初学者般的热情、专注,决定了在做某件事时能走多远,能做多好。” 该系列文章由python编写,遵循LeetBook 列表/腾讯的刷题顺序,所有代码已通过。每日3道,随缘剖析,希望风雨无阻,作为勉励自己坚持刷题的记录。
2. 两数相加
- 迭代:可改进之处,直接使用l1进行next而不是开辟新的空间
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
headnode = prenode = ListNode(1)
gian = 0
while(l1 or l2 or gian):
l1_val = l1.val if l1 else 0
l2_val = l2.val if l2 else 0
nownode = ListNode((l1_val+l2_val+gian)%10)
if l1_val + l2_val + gian>=10:
gian = 1
else: gian = 0
prenode.next = nownode
prenode = nownode
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return headnode.next
- 递归版本:想最后的结果or每一步的下一步需要什么,就是返回的值!【第一遍未写出】
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
sum_ = val1 + val2
l1.val = sum_ % 10
gain = 1 if sum_ > 9 else 0
if l1 and l1.next:
l1.next.val += gain
self.addTwoNumbers(l1.next,l2.next if l2 and l2.next else 0)
elif l2 and l2.next:
l1.next = l2.next
l1.next.val += gain
self.addTwoNumbers(l1,None)
elif gain:
l1.next = ListNode(val=1,next=None)
return l1
206. 反转链表
- 迭代:
class Solution(object):
def reverseList(self, head):
pre = None
cur = head
while cur:
# 记录当前节点的下一个节点
tmp = cur.next
# 然后将当前节点指向pre
cur.next = pre
# pre和cur节点都前进一位
pre,cur = cur,tmp
return pre
- 递归:
class Solution(object):
def reverseList(self, head):
# 递归终止条件是当前为空,或者下一个节点为空
if(head==None or head.next==None):
return head
cur = self.reverseList(head.next)
head.next.next = head
# 将head.next设置为空,是因为输入的头节点现在的next指向了第二个,递归后又指回来啦
head.next = None
# 递归地返回最后一个节点(也就是反转后的头节点)
return cur
21. 合并两个有序链表
- 迭代:
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
p1, p2 =l1,l2
head = ListNode(0,None)
tmp = head
# while p1 or p2:
# if not p2 or (p1 and p1.val<p2.val):
while p1 and p2:
if p1.val<p2.val:
tmp.next = p1
p1 = p1.next
else:
tmp.next = p2
p2 = p2.next
tmp = tmp.next
# 尽量直接连接而不是像上面注释的还不断通过while来移动指针
tmp.next = p1 if p1 is not None else p2
return head.next
- 递归:
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
elif l2 is None:
return l1
# 解决问题的过程就是递归的“归”的过程
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2