双指针法
- 指针设置:
- fast(right) 指针指向数组尾部,向前遍历迭代;
- slow(left) 指针指向数组头部,向后遍历迭代;
- 思路:
- 两指针数值相加,如果比目标值大,则向前移动 fast 指针;
- 如果比目标值小,则向后移动 slow 指针;
- 与目标值相等,则 slow、fast 指针即为目标值两数和;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0;
int right = numbers.size() - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return {left + 1, right + 1};
} else if (sum > target) {
--right;
} else {
++left;
}
}
return {-1, -1};
}
};