This problem is similar with Two Sum.
The solution is easy. Since they are sorted, we only need to get two pointers that point to head and tail respectively. Then move head one if the sum is smaller than the target and move the tail one if the sum if larger. Very classic two pointers problem.
vector<int> twoSum(vector<int> &nums, int target){
int len = nums.size();
vector<int> res;
if(len<2) return res;
int head=0; int tail=len-1;
while(head<tail)
{
int sum=nums[head]+nums[tail];
if(sum>target) tail--;
else if(sum<target) head++;
else
{
res.push_back(head);
res.push_back(tail);
return res;
}
}
return res;
}
The else if part could be replaced by a Conditional ternary operator which will be more elegant.