题目:
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
解法:
方法一
暴力求解法,时间复杂度 O(n2) ,略。
方法二
hash表,时间复杂度 O(n) ,代码如下
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> twoSum(vector<int> const &array, int target)
{
unordered_map<int, int> num;
vector<int> result;
int k = 1;
for (auto i : array)
num[i] = k++;
for (auto i : array)
{
int sub = target - i;
if (num.find(sub) != num.end())
{
result.push_back(num[i]);
result.push_back(num[sub]);
break;
}
}
return result;
}
方法三
排序后左右夹逼法,排序算法时间复杂度 O(nlogn) ,夹逼时间复杂度 O(n) ,总体时间复杂度 O(nlogn) 。代码如下
vector<int> twoSum(vector<int> &num, int target)
{
sort(num.begin(), num.end());
int i = 0;
int j = num.size() - 1;
vector<int> result;
while (i<j)
{
if ((num[i] + num[j]) == target)
{
result.push_back(i + 1);
result.push_back(j + 1);
break;
}
if ((num[i] + num[j]) < target)
i++;
else
j--;
}
return result;
}