1、题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
2、思路
程序中定义了一个map,存储key-value,key是vector中的元素值,value是该元素值对应的index索引值。对vector中元素进行遍历,每一次遍历,都会在map中查找结果,如果可以找到则返回,如果找不到,则将此元素值及其索引存入map中。
3、代码
//用时8ms
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::map<int, int> value_index;
int index = 0;
std::vector<int > result;
for (auto it = nums.begin(); it != nums.end(); it++) {
int another = target - *it;
auto f_index = value_index.find(another);
//若是找到则返回该元素的迭代器,否则返回尾迭代器
if(f_index == value_index.end()){
//如果没有找到,则将数据插入到map中
value_index[*it] = index;
} else{
//如果找到则返回结果
result.push_back((*f_index).second);
result.push_back(index);
break;
}
index++;
}
return result;
}
};