[LeetCode] 167. Two Sum II - Input array is sorted
Given a 1-indexed 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. Let these two numbers be numbers[index1]
and numbers[index2]
where 1 <= index1 < index2 <= numbers.length
.
Return the indices of the two numbers, index1
and index2
, added by one as an integer array [index1, index2]
of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Example 1:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:
Input: numbers = [2,3,4], target = 6 Output: [1,3] Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3:
Input: numbers = [-1,0], target = -1 Output: [1,2] Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
Constraints:
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers
is sorted in non-decreasing order.-1000 <= target <= 1000
- The tests are generated such that there is exactly one solution.
两数之和 II - 输入有序数组。
给定一个已按照 非递减顺序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。
你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题意是给一个已经按升序排好序的数组,请返回两个数字的下标,两个数字满足和为 target。因为是已经排好序的 array,所以用 two pointer 从两边往中间逼近,注意最后返回的下标 + 1。
时间O(n) - two pointer最坏情况下还是需要遍历所有元素
空间O(1)
Java实现
1 class Solution { 2 public int[] twoSum(int[] numbers, int target) { 3 int low = 0; 4 int high = numbers.length - 1; 5 while (low < high) { 6 int sum = numbers[low] + numbers[high]; 7 if (sum == target) { 8 return new int[] {low + 1, high + 1}; 9 } else if (sum > target) { 10 high--; 11 } else { 12 low++; 13 } 14 } 15 return new int[] {-1, -1}; 16 } 17 }
JavaScript实现
1 /** 2 * @param {number[]} numbers 3 * @param {number} target 4 * @return {number[]} 5 */ 6 var twoSum = function(numbers, target) { 7 // corner case 8 if (numbers === undefined || numbers.length < 2) { 9 return [-1, -1]; 10 } 11 12 // normal case 13 let start = 0; 14 let end = numbers.length - 1; 15 while (start < end) { 16 const sum = numbers[start] + numbers[end]; 17 if (sum === target) { 18 return [start + 1, end + 1]; 19 } else if (sum < target) { 20 start++; 21 } else { 22 end--; 23 } 24 } 25 return [-1, -1]; 26 };