1、两数之和
解法一 暴力法(2个for循环)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for ii in range(len(nums)):
for jj in range(ii+1, len(nums)):
if nums[ii]+nums[jj] == target:
return [ii,jj]
解法二 哈希表法
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash = {}
for ii, num in enumerate(nums):
if target-num in hash:
return [hash[target-num],ii]
hash[num] = ii
哈希表[key]=value
key是数值
value是索引值
便历索引,数值用枚举enumerate;
2、两数相加
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
# 初始化链表ListNode()表示链表,head表示静止表头,tree表示动态指针;val是相加后/10的余数,tmp是商;
head = tree = ListNode()
val = tmp = 0
# 当三者有一个不为空时,继续循环
while tmp or l1 or l2:
val = tmp
if l1:
val = l1.val + val
l1 = l1.next
if l2:
val = l2.val + val
l2 = l2.next
tmp = val // 10
val = val % 10
tree.next = ListNode(val)
tree = tree.next
return head.next