题目:
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
分析:
数组,找到两个值,使得其和与目标值一样。返回的是两个数的下标,同时,这个下标是从0开始计算的。
题目表示,有且只有一个解。
思路:
hashtable,这样的话,就可以免去O(N^2)的复杂度。同时,hashtable的搜索很快,因此基本就是O(N)啦!
因为,题目要求返回的是数据的下标,因此,不能采用排序的方式来实现,因为排序会改变数值的下标。
代码:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> store;
for(int i = 0; i < nums.size(); ++i)
{
auto itr = store.find(target - nums[i]);
if(itr != store.end())
return vector<int> {store[target - nums[i]]+1,i+1};
else
store[nums[i]] = i;
}
}