题目描述
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
问题分析
这道题初一看,应该会有三种解决方案:
- 直接暴力搜索,此时时间复杂度是o(n^2),显然这种方法并不可行
- 采用hash,存储每一个数值的对应下表,这个复杂度O(n)
- 对这个数组进行排序,然后进行查找,复杂度是O(nlogn),但是这个题要输出的是下表,并不合适