给定一个整型数组和一个目标整数,返回数组中和等于目标的两个元素的下标。
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
| 1 |  | 
思路一
双重循环来判断,时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。
Python 3 实现如下:
| 1 |  | 
思路二
- 首先进行排序,复杂度 $O(n\log n)$;
- 然后有序数组找到两个数a,b,使得$a + b == target$,复杂度 $O(n)$;
- 最后在原数组中找到 $a, b$ 下标,复杂度 $O(n)$。
总的时间复杂度 $O(n \log n)$。
Python 3 实现如下:
| 1 |  | 
思路三
用hash table实现,遍历一遍数组,时间复杂度 $O(n)$,空间复杂度 $O(n)$。
- 
    hash table中key为当前元素,value为当前元素对应的下标; 
- 每次判断目标与当前元素的差是否在hash table内,如果是则返回hash table中该差的value值(即原元素的下标);
- 将当前目标存入hash table
Python 3实现如下:
| 1 |  | 
Note
- 使用Python 3 时,用enumerate(nums)方法比range(len(nums))遍历数组会更快。
 
          