题目
:::info
https://leetcode-cn.com/problems/two-sum/
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
你可以按任意顺序返回答案。
:::
题解
初始思路
遍历数组:
- 用 target 减去当前的数
- 看得到的数是否在剩下的数组内
```python
def twoSum(nums, target):
“””
:type nums: List[int]
:type target: int
:rtype: List[int]
“””
for i, n1 in enumerate(nums):
n2 = target-n1if n2 in nums[i+1:]:idx = nums[i+1:].index(n2)return [i, i+idx+1]
nums = [2,7,11,15] target = 9 print(twoSum(nums,target))
执行用时:20 ms, 在所有 Python 提交中击败了66.33%的用户
内存消耗:12.9 MB, 在所有 Python 提交中击败了97.01%的用户
<a name="Y50v3"></a>
### 官方思路
和我差不多,但不同的是它通过字典来储存每个数的index,字典的本质是通过建立一个hash表,将key直接映射到value的地址上,因此查询速度为 O(1),缺点是占用了更多内存。
```python
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashtable=dict()
for i, n1 in enumerate(nums):
n2 = target-n1
if n2 in hashtable:
idx = hashtable[n2]
return [i, idx]
hashtable[n1]=i
nums = [-10,-1,-18,-19]
target = -19
print(twoSum(nums,target))
