Question
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].
Code
#include<iostream>
#include<unordered_map>
#include<vector>
using namespace std;
class Solution {
public:
vector <int> twoSum(vector<int>& nums, int target) {
vector <int> result;//存放结果
unordered_map<int, int> m;//m初始为空
for (int i = 0; i < nums.size(); i++) {
if (m.find(target - nums[i]) != m.end()) {
result.push_back(m[target - nums[i]]);
result.push_back(i);
return result;//如果找到匹配值,返回结果,跳出循环
}
m[nums[i]] = i;//如果没有找到匹配值,将其插入m
}
return result;
}
};
int main() {
Solution so;
vector<int> nums = {2,7,11,15};
vector<int> result;
int target = 9;
result = so.twoSum(nums,target);
cout << result[0] << " " << result[1] << endl;
system("pause");
return 0;
}