题目:
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].
思路:
找到 a
,找到 b
,让 a + b = target
。那么肯定得遍历,遍历的过程中,记录什么,成了思考的关键。
既然是配对,那么 kv 结构是非常合适的,于是上了 Hash 表。让 key 就是要找的 b
,让 value 记录 a
的 index,也就是结果需要的索引。
代码:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/*
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> record;
for (int i = 0; i != nums.size(); i++)
{
auto find = record.find(nums[i]);
if (find != record.end())
return{ find->second, i };
else
record.emplace(target - nums[i], i);
}
return{ -1, -1 };
}
};