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

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


Timeline

Timeline

2025-11-10

init

Two pointers

Problem:

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

123456789101112131415161718192021
#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 };	}};
Loading comments…