Question
Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
Train of thought one: Traverse two times, Time Complexity O (n2) O (1) space;
Idea two: using hash table, directly traversing one side to see if there is a key (target-x) exists; time complexity O (n), space O (n)
Code
Class Solution {
Public
Vector<int> twosum (vector<int> &numbers, int target) {
Map<int,int> sum;
vector<int> Res;
for (int i=0;i<numbers.size (); i++) {
int x = numbers[i];
if (Sum.count (target-x)) {
Res.push_back (Sum[target-x] + 1);
Res.push_back (i + 1);
return res;
}else{
SUM[X] = i;
}
}
}
};
Leecode--Twosum