问题描述:
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:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
以下为两种解答方法,第一种为暴力匹配法(注释的部分,时间复杂度为O(n2)),第二种为哈希表法(时间复杂度为O(n)):
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
/*for (int i = 0; i < nums.size() - 1; i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
if (nums[i] + nums[j] == target)
return{ i, j };
}
}*/
std::unordered_map<int,int>hash_map;
std::unordered_map<int,int>::iterator it;
std::pair<int,int> pairs;
std::vector<int>outputArr;
int input_len = nums.size();
for (int i=0;i<input_len;i++)
{
pairs.first=target - nums[i];
pairs.second=i;
if(hash_map.find(nums[i])!=hash_map.end())
{
outputArr.push_back(hash_map[nums[i]]);
outputArr.push_back(i);
return outputArr;
}
else
{
hash_map.insert(pairs);
}
}
}
};