0167. Two Sum II - Input array is sorted
Easy | Two Pointer | 56 ms (95.70%), 14.8 MB (32.12%)
Source: LeetCode - Two Sum II - Input array is sorted GitHub: Solution / Performance
Given an array of integers numbers
that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target
number.
Return the indices of the two numbers (1-indexed) as an integer array answer
of size 2
, where 1 <= answer[0] < answer[1] <= numbers.length
.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Since there is exactly one solution, two-pointers with dynamically adjusted indexes could help to solve.
Starting with the left- and right-most elements, we sum up them to see whether the result meets the target value.
If the result is greater than the target, we move the right-pointer forward.
If the result is less than the target, we move the left-pointer backward.
Last updated
Was this helpful?