leetcode Two Sum 两数之和

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
方案:hash查找
#include<iostream>
#include<vector>
#include<unordered_map>
vector<int> twosum(vector<int>& v,int target)
{
    unordered_map<int,int> m;
    vector<int> v1;
    int val;
    for(int i=0;i<v.size();i++)
    {
        m[v[i]]=i;
    }
    for(int j=0;j<v.size();j++)
    {
        val=target-v[j];
        //key存在且不能是自身
        if(m.count(val) && m[val]!=j)   
        {
            v1.push_back(j);
            v1.push_back(m[val]);
            break;
        }
    }
    return v1;
}
int main()
{
    vector<int> v={2,7,11,15};
    //vector<int> vv=twosum(v,4);
    vector<int> vv=twosum(v,9);
    for(auto iter:vv)
        cout<<iter<<" ";
}

猜你喜欢

转载自blog.csdn.net/acttell/article/details/80954185
今日推荐