Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add upp to the target, where index1 must be less than index2.
Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers = {2, 7, 11, 15}, target = 9;
output: index1 = 1, index2 = 2
Ideas: 1. two loop to get the target.
2. use
1. Two loop O(n2) Time Limit Exceeded
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
int size = numbers.size();
if(size < 2) return result;
for(int i = 0; i < size - 1; i++)
{
for(int j = i+1; j < size; j++)
{
if(numbers[i] + numbers[j] == target)
{
result.push_back(i+1);
result.push_back(j+1);
return result;
}
}
}
return result;
}
};
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
int size = numbers.size();
if(size < 2) return result;
unordered_map<int, int> mymap;
for(int i = 0; i < size ; i++)
{
mymap[numbers[i]] = i;
}
for(int i = 0; i < size; i++)
{
int gap = target - numbers[i];
if(mymap.find(gap)!= mymap.end() && mymap[gap] != i) //bug1
{
result.push_back(i + 1);
result.push_back(mymap[gap] + 1);
break;
}
}
return result;
}
};