Cover image for Interview Classic 150 Questions P167 Two Sum II - Input Array Is Sorted

Interview Classic 150 Questions P167 Two Sum II - Input Array Is Sorted


Timeline

timeline

2025-11-10

init

two pointers

Title:

Two pointers point to the head and tail respectively. If the sum of the values pointed by the two pointers is greater than target, move the tail pointer left to decrease the sum; if the sum is less than target, move the head pointer right to increase the sum.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
using std::vector;

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
int i = 0, j = numbers.size() - 1, curr;
while (i < j) {
curr = numbers[i] + numbers[j];
if (curr < target) {
i++;
} else if (curr > target) {
j--;
} else {
break;
}
}
return { i + 1, j + 1 };
}
};