|
| 1 | +--- |
| 2 | +comments: true |
| 3 | +difficulty: easy |
| 4 | +# Follow `Topics` tags |
| 5 | +tags: |
| 6 | + - Array |
| 7 | + - Two Pointers |
| 8 | + - Binary Search |
| 9 | +--- |
| 10 | + |
| 11 | +# [167. Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/) |
| 12 | + |
| 13 | +## Description |
| 14 | + |
| 15 | +You are given a 1-indexed array of integers called numbers, which is already sorted in increasing order. |
| 16 | + |
| 17 | +Your goal is to find two numbers in this array that add up to a given target value. Let’s call their positions index1 and index2, where: |
| 18 | + |
| 19 | +1 <= index1 < index2 <= numbers.length (i.e., index1 comes before index2 in the array). |
| 20 | + |
| 21 | + |
| 22 | +**Example 1:** |
| 23 | +``` |
| 24 | +Input: numbers = [2, 5, 6], target = 11 |
| 25 | +Output: [2, 3] |
| 26 | +Explanation: The sum of 5 and 6 is 11. Therefore, index1 = 2, index2 = 3. We return [2, 3]. |
| 27 | +``` |
| 28 | + |
| 29 | +**Example 2:** |
| 30 | +``` |
| 31 | +Input: numbers = [1, 2, 5, 6], target = 7 |
| 32 | +Output: [2, 3] |
| 33 | +Explanation: The sum of 2 and 5 is 7. Therefore, index1 = 2, index2 = 3. We return [2, 3]. |
| 34 | +``` |
| 35 | + |
| 36 | + |
| 37 | +**Constraints:** |
| 38 | + |
| 39 | +`2 <= numbers.length <= 3 * 104` |
| 40 | + |
| 41 | +`-1000 <= numbers[i] <= 1000` |
| 42 | + |
| 43 | +`numbers is sorted in non-decreasing order` |
| 44 | + |
| 45 | +`-1000 <= target <= 1000` |
| 46 | + |
| 47 | +`The tests are generated such that there is exactly one solution.` |
| 48 | + |
| 49 | + |
| 50 | +## Solution |
| 51 | + |
| 52 | +Initialize two pointers, one at the front and one at the end. Check the sum of the two pointers. If the target is greater than the sum, increase the left pointer; otherwise, decrease the right pointer. Repeat this process until the sum equals the target or the two pointers meet. |
| 53 | + |
| 54 | +```java |
| 55 | +class Solution { |
| 56 | + public int[] twoSum(int[] numbers, int target) { |
| 57 | + int left = 0, right = numbers.length - 1; |
| 58 | + |
| 59 | + while (left < right) { |
| 60 | + int sum = numbers[left] + numbers[right]; |
| 61 | + if (sum == target) { |
| 62 | + return new int[] {left + 1, right + 1}; |
| 63 | + } else if (sum < target) { |
| 64 | + left++; |
| 65 | + } else { |
| 66 | + right--; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return result; |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +## Complexity |
| 76 | + |
| 77 | +- Time complexity: $$O(n)$$ |
| 78 | +<!-- Add time complexity here, e.g. $$O(n)$$ --> |
| 79 | + |
| 80 | +- Space complexity: $$O(1)$$ |
| 81 | +<!-- Add space complexity here, e.g. $$O(n)$$ --> |
0 commit comments