Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

Maps and Vectors -STL in C++

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;

    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...