//
// Created by tannzh on 2020/6/9.
//
/*
* 标题: 两数之和
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
*
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
* 示例:
* 给定 nums = [2, 7, 11, 15], target = 9
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
* */
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int, int> record;
for(auto i = 0; i != nums.size(); ++i) {
auto found = record.find(nums[i]);
if(found != record.end()) {
return {found->second, i};
}
record.emplace(target - nums[i], i);
}
return {-1, -1};
}
};
int main(int argc, char **argv)
{
Solution s;
std::vector<int> nums{2, 7, 11, 15};
int target = 9;
auto result = s.twoSum(nums, target);
std::cout << "result = ";
for(auto i : result){
std::cout << result[i] << " ";
}
std::cout << std::endl;
return 0;
}
解题思路
这道题有点像找配对。找到 `a`,找到 `b`,让 `a + b = target`。那么肯定得遍历,遍历的过程中,记录什么,成了思考的关键。
既然是配对,那么 kv 结构是非常合适的,于是上了 Hash 表。让 key 就是要找的 `b`,让 value 记录 `a` 的 index,也就是结果需要的索引。
这样思路就很简单明了了。