数组有序,通过双指针求和,双指针先位于两端
如果等于目标值,则返回
小于目标值,需要增大,所以左指针自增
大于目标值,需要减少,所以右指针自减
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> r;
int n = numbers.size();
for (int i = 0, j = n - 1; i < j;)
{
int sum = numbers[i] + numbers[j];
if (sum == target)
{
r.push_back(i + 1);
r.push_back(j + 1);
break;
}
else if (sum > target)
{
--j;
}
else
{
++i;
}
}
return r;
}
};