题目名称:两数之和
题目编号:1
题目介绍:
个人思路:遍历寻找
具体代码实现:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 方法一:遍历寻找
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []
可以看出来,代码执行效率很低。
根据题解,学习到新的解决方法:哈希表。
Python中字典使用哈希保存,所以,改进后的代码如下:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 方法二:哈希表
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []
可以看出来,时间,空间都进步了!