LeetCode 算法题库学习(2)

Angie ·
更新时间:2024-09-21
· 808 次阅读

两数相加 题目描述:

timu

解题思路: 第一种:这个方法是比较常规的方法,没有什么花里胡哨。一开始也是先定义头结点,然后对p进行修改。然后进行迭代,然后用temp来表示往后进位的数,再加上前面链表里的对应元素,也就是Sum,再对10 取余,得出来的结果放到p.next,然后从p.next开始找下一位数,以此类推。算到链表最后,如果说temp仍然是大于零的,说明Sum大于10,要进位,所以链表p最后元素就是1 。 时间复杂度:O(n) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: lino = ListNode(0) p = lino temp = 0 while l1 or l2: a = l1.val if l1 else 0 b = l2.val if l2 else 0 Sum = a + b + temp temp = Sum // 10 p.next = ListNode(Sum % 10) p = p.next if l1: l1 = l1.next if l2: l2 = l2.next if temp > 0: p.next = ListNode(1) return lino.next

2

第二种:这个方法和第一种类似,用到的是递归的方法。首先同理先判断l1l2是不是为空。这个方法和前一个不同在于这里直接对p进行修改,最后返回p。先求得两个链表对应元素之和,然后让这个和对10取余,容易发现,如果余数小于10,则这个和直接被放在p的相应位置,如果大于等于10,则后面会将p.nextListNode(1)一起递归,也就是说下一个p.next会加1,也就是进了一位。最后递归完成输出p# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: if not l2: return l1 if not l1: return l2 temp = l1.val + l2.val p = ListNode(temp%10) p.next = self.addTwoNumbers(l1.next, l2.next) if temp >= 10: p.next = self.addTwoNumbers(ListNode(1), p.next) return p

3

第三种:这个方法我觉得还可以,因为它提供了一个新思路,就是我们可以换成str的形式来解决这个链表问题。虽然说速度各方面不是特别快。比较容易理解,这里就不细说了。 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: node = l1 result1 = "" while node is not None: result1 = str(node.val) + result1 node = node.next result2 = "" node = l2 while node is not None: result2 = str(node.val) + result2 node = node.next Sum = str(int(result1) + int(result2)) l3 = l4 = ListNode(0) for index in range(len(Sum), 0, -1): l3.next = ListNode(int(Sum[index - 1])) l3 = l3.next return l4.next

3


作者:Justpcode



题库 leetcode 学习 算法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号