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 up 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
更新:这里自定义了一个struct,重载了比较操作符的,但更佳的方法其实还是使用stl的库,带hash的数据结构非常适合在这里使用,因为查找效率为O(1),这里使用unordered_map比较好,使用指南如下:
http://blog.youkuaiyun.com/oabid/article/details/4562577
class Solution {
public:
struct num2index
{
int index;
int num;
bool operator < (const num2index& val) const
{
return num < val.num;
}
};
vector<int> twoSum(vector<int> &numbers, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> res(2,0);
int length = numbers.size();
vector<num2index> result(length);
for(int i = 0; i < length ; i++)
{
result[i].index = i;
result[i].num = numbers[i];
}
sort(result.begin(),result.end());
int start = 0;
int end = length - 1;
while(start < end)
{
int sum = result[start].num + result[end].num;
if(sum == target)
{
if(result[start].index < result[end].index)
{
res[0] = result[start].index + 1;
res[1] = result[end].index + 1;
}
else
{
res[0] = result[end].index + 1;
res[1] = result[start].index + 1;
}
return res;
}
else if(sum < target)
start++;
else
end--;
}
return res;
}
};