Twosum
Given an array of Integers,find two numbers such this they add up to a specific target number.
The function two Sum should return indices of the two numbers such this they add up to the Target,where index1 is Les S than Index2.
Please note this your returned answers (both INDEX1 and index2) are not zero-based.
You may assume this each input would have exactly one solution.
Input:numbers={2, 7, one, target=9
Output:index1=1, index2=2
Method One:
Brute Force solution
class Solution1
{public
:
vector<int> twosum (vector<int> &num, int target)
{
vector<int> rs;
for (int i = 0; i < num.size (); ++i)
{for
(int j = i + 1; j < Num.size (); j + +)
{
if (Num[i] + num[ J] = = target)
{
Rs.push_back (i + 1);
Rs.push_back (j + 1);
return RS;
}
}
return RS;
}
;
Method Two:
With a hash table, store each number corresponding to the subscript
class Solution2
{public
:
vector<int> twosum (vector<int> &num, int target)
{
vector<int> rs;
Unordered_map<int, int> m;
int i;
for (i = 0; i < num.size (); i++)
m[num[i]] = i;
for (i = 0; i < num.size (); i++)
{
int sub = target-num[i];
if (M.find (sub)!= m.end () && m[sub] > i)
{
Rs.push_back (i + 1);
Rs.push_back (M[sub] + 1);
break;
}
}
return RS;
}
;