题目: 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
链接:两数之和
解题思路
用空间来换取时间
如果不借助空间的话,只能通过双重循环来解决这种方法的时间复杂度是O(n^2)
利用HashMap来存储已经遍历过的num,因为题目要求返回数组下标所以map存储的结构形式为: nums[i]为键,i为值
在遍历的过程中,每遍历一个元素就执行map.get(target - nums[i])操作,
如果map中存在元素=target-num[i]则,直接返回结果;
不存在,则把num[i],i放进map.
重复上述过程,知道遍历完所有元素.
由于HashMap在没有Hash冲突的时候查询的时间复杂度是O(1),
遍历一维数组的时间复杂度是O(n)
所以总的时间复杂度最好的情况下能达到O(n)
代码
Java
class Solution {
public int[] twoSum(int[] nums, int target) {
//先从HashMap中get,如果没有就put
Map<Integer,Integer> map = new HashMap<>(nums.length * 2);
for(int i = 0; i < nums.length; i++) {
if (map.get(target - nums[i]) != null) {
return new int[]{map.get(target - nums[i]),i};
}
map.put(nums[i], i);
}
return null;
}
}
python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = {}
for index,num in enumerate(nums):
if (target - num) in hashmap:
return [hashmap[target - num], index]
hashmap[num] = index
return None
```
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200805233702706.png)