#include<iostream>
#include<unordered_map>
#include<vector>
std::vector<int> twoSum(std::vector<int> &numbers, int target)
{
std::unordered_map<int, int> mymap;
std::vector<int> result;
for(int i = 0; i < numbers.size(); i++)
{
mymap[numbers[i]] = i;
}
for(int i = 0; i < numbers.size(); i++)
{
int restVal = target - numbers[i];
if(mymap.find(restVal) != mymap.end())
{
int index = mymap[restVal];
if(index == i)
{
continue;
}
else
{
if(index < i)
{
result.push_back(index+1);
result.push_back(i+1);
break;
}
else
{
result.push_back(i+1);
result.push_back(index+1);
break;
}
}
}
}
return result;
}
int main()
{
std::vector<int> numbers;
numbers.push_back(1);
numbers.push_back(5);
numbers.push_back(2);
numbers.push_back(6);
numbers.push_back(4);
int target = 9;
std::vector<int> res = twoSum(numbers, target);
for(int i = 0; i < res.size(); i++)
{
std::cout<<res[i]<<std::endl;
}
}
leetcode--twoSum
最新推荐文章于 2024-08-15 05:02:54 发布