1.问题描述
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
2.问题分析
方法1,暴力搜索,复杂度O(n^2)
方法2,hash,用一个hash表,存储每个数对应的下标,空间复杂度O(n),时间复杂度O(n)。
3.代码
class Solution
{
public:
vector<int> twoSum(vector<int> &num, int target)
{
unordered_map<int, int>mapping;
vector<int> result;
for(int i = 0;i < num.size();++i)
mapping[num[i]] = i;
for(int i = 0;i < num.size();++i)
{
const int gap = target - num[i];
if(mapping.find(gap) != mapping.end())
{
result.push_back(i+1);
result.push_back(mapping[gap]+1);
break;
}
}
return result;
}
};
4.总结
本题的关键在于:
1、使用hash表存储数据,使用O(n)的空间;
2、利用hash表每次O(1)的查找时间,使得总的实际复杂度为O(n)。