正确但是超时的解法
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int>res;
for(int i=0;i<numbers.size();i++)
{
if(find(numbers.begin()+i+1,numbers.end(),target-numbers[i])!=numbers.end())
{
res.push_back(i+1);
res.push_back(1+(find(numbers.begin()+i+1,numbers.end(),target-numbers[i])-numbers.begin()));
break;
}
}
return res;
}
};
下面给出一个可以在O(N)的时间内运行完毕的算法,这采用了双指针的思想。
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int>res;
int i=0;
int j=numbers.size()-1;
while(i<j)
{
if(numbers[i]+numbers[j]==target)
{
res.push_back(i+1);
res.push_back(j+1);
break;
}
if(numbers[i]+numbers[j]>target)
{
j--;
}
else
{
i++;
}
}
return res;
}
};