1.题目
https://leetcode-cn.com/problems/add-two-numbers/
2.个人题解
# 第一次完美提交,和官方答案思路一样,记录下class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = nextclass Solution: def addTwonumbers(self, l1, l2) : new = ListNode() # 初始化 head = new temp = 0 sums = 0 while l1 or l2: if l1 and l2: sums = l1.val + l2.val + temp if sums >= 10: temp = 1 sums = sums - 10 else: temp = 0 l1 = l1.next l2 = l2.next elif l1 or l2: if temp == 0: if l1: new.next = l1 new = l1 l1 = None break elif l2: new.next = l2 new = l2 l2 = None break elif temp == 1: if l1: sums = l1.val + temp l1 = l1.next elif l2: sums = l2.val + temp l2 = l2.next if sums >= 10: temp = 1 sums = sums - 10 else: temp = 0 r = ListNode() r.val = sums sums = 0 new.next = r new = r if not l1 and not l2 and temp: r = ListNode() r.val = 1 new.next = r return head.next# debugdebug = Solution()l1 = ListNode(6, ListNode(1, ListNode(2)))l2 = ListNode(4, ListNode(4))d = debug.addTwonumbers(l1, l2)while d: print(d.val) d = d.next
3.题目
https://leetcode-cn.com/problems/two-sum/
4.个人题解
# 查找-哈希表法from typing import Listclass Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: res = [] temp = dict() for i, num in enumerate(nums): temp[num] = i for i, num in enumerate(nums): if target-num in temp.keys() and i != temp[target-num]: return [i, temp[target-num]]