题目:
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.
函数返回两个数的下标(注意返回的这个下标是在数组中的下标+1),其中下标1必须小于下标2.注意返回的答案不能是0.
You may assume that each input would have exactly one solution.
你可以假定每个输入都有一个正确的结果。
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2(返回的下标是在数组中的下标+1)
注意:可以采用暴力法搜索,但是复杂度为O(n^2),答案通不过,会超时。
本题可以采用哈希表,直接寻址法,map的键为数组的数,值为对应的下标,复杂度为O(n).
代码:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
unordered_map<int, int> mapping;//定义非排序map
vector<int> ivec;//返回结果
for(int i=0;i < numbers.size();i++)
{
mapping[numbers[i]]=i;//把数组的数和下标存储到man中的键值里
}
for(int i = 0;i < numbers.size() ;i++)
{
int gap=target-numbers[i];//找到差值即找到符合条件的下标
if(mapping.find(gap) != mapping.end() && mapping[gap] > i)//迭代器没有到最后,gap对应的下标比i大
{
ivec.push_back(i + 1);
ivec.push_back(mapping[gap] + 1);
break;
}
}
return ivec;
}
};