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].
思考
前面有遇到类似的,但是给出的数组是有序排列的,这种情况下可采用两个指针分别移动的方式,一个在前、一个在后,大了后指针后退,小了前指针前进;
因此,本想用这种方法,但是需要返回的是下标,而排序后,下标就乱掉了,因此这种方法不适合。
接着,既然是查找问题,自然而然想到了哈希,所以,现将数据存入哈希,然后进行查找即可。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> temp;
for (int i = 0; i < nums.size(); i++)
{
if (temp.find(nums[i]) == temp.end())
{
temp.insert(make_pair(nums[i], i));
}
}
vector<int> new_index;
int j;
for (int i = 0; i < nums.size(); i++)
{
if (temp.find(target - nums[i]) != temp.end())
{
j=temp.find(target - nums[i])->second;
if (i == j)
continue;
//cout << i <<"---"<< j<<endl;
new_index.push_back(i);
new_index.push_back(j);
break;
}
}
return new_index;
}
};