1.两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解答:
# 建立哈希表
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i, m in enumerate(nums):
dict[m] = i
for i, m in enumerate(nums):
j = dict.get(target - m)
if j is not None and i != j:
return [i, j]
该方法建立一个字典,将列表的值作为字典的Key,列表索引作为字典的value,故只用遍历一遍字典即可判断是否存在相应的值。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i, m in enumerate(nums):
if dict.get(target - m) is not None:
return [dict.get(target - m), i]
dict[m] = i
两数相加
# 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:
a, b, p, carry = l1, l2, None, 0
while a or b:
# a和b节点值相加,然后加上进位carry
val = (a.val if a else 0) + (b.val if b else 0) + carry
carry = val/10 if val >= 10 else 0
val = int(val%10)
p, p.val = a if a else b, val
a = a.next if a else None
b = b.next if b else None
p.next = a if a else b
if carry:
p.next = ListNode(carry)
return l1