问题描述
任何人都可以解释这个代码工作吗?它是在向量中找到2个元素的索引添加到产生给定的目标。我不明白STL如何工作。
Can anyone explain this code working?It is to find index of 2 elements in vector that add to produce the given target.I don't understand how STL works in this.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int>m;
vector<int>v;
if(nums.size()==0)
{
return v;
}
for(int i=0;i<nums.size();i++)
{
if(m.find(nums[i])==m.end())
{
m[target-nums[i]]=i+1;
}
else
{
v.push_back(m[nums[i]]);
v.push_back(i+1);
}
}
return v;
}
};
推荐答案
说向量是{8,4,3,2,5},目标是10.你找到的第一个数字是8,所以现在你知道你正在寻找一个2(因为8 + 2是10)。所以你添加新的目标2和索引8(这是1,因为索引是1)到地图。下一个数字是4所以现在你正在寻找6,所以6和索引2被添加到地图。现在地图看起来像这样
It's pretty easy. Say the vector is { 8, 4, 3, 2, 5 } and the target is 10. First number you find is 8, so now you know that you are looking for a 2 (because 8 + 2 is 10). So you add the new target 2 and the index of 8 (which is 1 because the indexes are 1 based) to the map. Next number is 4 so now you are looking for 6, so 6 and the index 2 get added to the map. Now the map looks like this
2 ==> 1
6 ==> 2
最后,您会在地图中找到其中一个目标我们知道2的索引,因为我们刚刚找到它,所以我们可以输出这两个索引。
Eventually you'll find one of the targets in the map (in this case we'll find a two), the map gives us the index of the original 8, and we know the index of the 2 because we've just found it, so we can output both indexes.
代码可以改进,但我认为它可以工作。
The code could be improved, but I think it works.
这篇关于地图和向量-STL在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!