- tags: LeetCode101,Sorting,Two Pointers
Key ideas:
- Move both sides to inwards.
- If the sum value less than target, move left pointer.
- Otherwise move right poinger.
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int S, l = 0, r = numbers.size() - 1;
vector<int> res(2, 0);
while (l < r) {
S = numbers[l] + numbers[r];
if (S == target) {
break;
}
if (S < target) {
l++;
} else {
r--;
}
}
res[0] = l + 1;
res[1] = r + 1;
return res;
}
};