1. 题目
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].
2. 思路
建立hashmap,去查找余数是否存在。
3. 代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
_map.clear();
int size = nums.size();
for (int i = 0; i < size; i++) {
int cur = nums[i];
int need = target - cur;
auto f = _map.find(need);
if (f != _map.end()) {
res.push_back(f->second + 1);
res.push_back(i + 1);
return res;
}
_map[cur] = i;
}
return res;
}
private:
unordered_map<int, int> _map;
};