Problem: 1. 两数之和
思路
1.遍历整个数组,对于每个数字num,使用taget-num得到另一个数字
2.创建字典用于存储遍历之后的数字
3.使用if条件判断字典中是否存在taget-num之后的数字
4.满足条件后,返回结果
解题方法
哈希表解法
复杂度
- 时间复杂度:
添加时间复杂度,O(n)O(n)O(n)
- 空间复杂度:
添加空间复杂度,O(n)O(n)O(n)
Code
Python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_map = {}
for i, x in enumerate(nums):
if target - x in hash_map:
return [i, hash_map[target - x]]
hash_map[x] = i