Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...