原题目:
Given an array of integers that is already sorted in ascending order, 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(n^2),不过很不幸,结果超出时间限制;
算法二是通过一重循环穷举第一项,同时对第二项进行二分查找(给定数组已排好序),复杂度为O(nlogn),虽然通过,但是效率还不是很高;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> ans;
int i, j = -1;
for(i=0; i<numbers.size(); i++)
{
int l = 0, h = numbers.size()-1;
while(l <= h)
{
if(numbers[(l+h)/2] == (target-numbers[i]))
{
j = (l + h) / 2;
if(j == i) j ++;
break;
}
else if(numbers[(l+h)/2] < (target-numbers[i]))
l = (l + h) / 2 + 1;
else h = (l + h) / 2 - 1;
}
if(j != -1) break;
}
ans.push_back(i+1);
ans.push_back(j+1);
return ans;
}
};
算法三:短小精悍,且高效,复杂度为O(n)。设定两个变量i和j分别指向数组开头或者结尾,然后对向收缩,若numbers[i] + numbers[j]等于target,结束;若numbers[i]+numbers[j]<target,则i++;否则j++。详见代码:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> ans;
int i = 0, j = numbers.size()-1;
while(i < j)
{
if(numbers[i] + numbers[j] == target) break;
else if(numbers[i] + numbers[j] < target) i ++;
else j --;
}
ans.push_back(i+1);
ans.push_back(j+1);
return ans;
}
};