【Leetcode】167_两数之和 II - 输入有序数组
题目
思路
之所以记录这道题目是因为这里用到对撞指针的办法:分别设置指向数组头和尾的指针i、j,然后将数组中i、j对应的位置的值相加,若大于target则 j--,若小于target则 i++。注意,这个方法是一定会遍历所有的可能为答案的i、j组合的,与我之前写过的盛最多水的容器类似,所以这里就不再作证明,其实这两道题目的思想感觉也很相似。
代码
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i = 0, j = numbers.size()-1;
vector<int> ans;
while(j > i) {
int num = numbers[i]+numbers[j];
if(num == target) {
ans.push_back(i+1);
ans.push_back(j+1);
return ans;
}
else if(num > target)
j--;
else
i++;
}
return ans;
}
};