题目
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
分析
这道题借用STL中的map结构求解比较简单
声明一个int到int的map用于将数组中的数及其下标联系起来
遍历一遍数组
如果target减去当前元素存在于map中,则将当前下标i和map[target - nums[i]]即为答案
否则将当前元素及其下标添加到map中
代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> m;
vector<int> result;
for (int i = 0;i < nums.size();i++)
{
if (m.count(target - nums[i]))
{
result.push_back(i);
result.push_back(m[target - nums[i]]);
return result;
}
m.insert(make_pair(nums[i],i));
}
}
};