Question
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
问题解析:
给定升序排序数组,找到两个和为给定数字的元素,返回二者位置。注意index1 < index2,且不使用重复元素。
Answer
Solution 1:
左右两指针相加靠近。
- 注意题目与
LeetCode-1:Two Sum存在不同的地方,本题要求index1 < index2,可以使用除与LeetCode-1相同的HashMap之外其他的方法。 - 题中要求index1 < index2,那么我们可以利用这样的性质,设置左右两个指针,从两端向中间逼近,每次都用两个数判断是否等于目标值,等于则返回,不等则判断大小,增减左右指针。
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0;
int right = numbers.length-1;
while (numbers[left] + numbers[right] != target){
if (numbers[left] + numbers[right] > target){
right--;
}else{
left++;
}
}
return new int[]{left+1, right+1};
}
}
- 时间复杂度:O(n);空间复杂度:O(1)
有序数组两数之和

本文介绍了一种在已排序数组中寻找两数之和为目标值的高效算法。通过使用左右双指针技术,实现了一次遍历即可找到符合条件的两个数,并返回它们的下标。该方法的时间复杂度为O(n),空间复杂度为O(1)。
851

被折叠的 条评论
为什么被折叠?



