Two Sum
Description:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
给定一个整数数组,返还和为特定值target的两个数的下标,其中同一数值不可使用两次。
Solution:
#include<iostream>
#include<unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> um;
int n = nums.size();
int i;
vector<int> res(2);
for (i = 0; i < n; ++i) {
if (um.find(target - nums[i]) != um.end()) {
res[0] = um[target - nums[i]];
res[1] = i;
break;
}
else {
um[nums[i]] = i;
}
}
um.clear();
return res;
}
};
int main()
{
Solution rr;
vector <int> rrr;
vector<int> xx = { 1, 2, 3, 4, 5 };
int tt = 6;
rrr=rr.twoSum(xx, tt);
for (int j = 0; j < rrr.size(); ++j)
{
cout << rrr[j] << endl;
}
system("pause");
return 0;
}