题目
level:easy
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.
Note:
- 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: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
解题思路
根据题目说明,数组中元素呈单调递增排列,并假设每个入参只有一个结果且不能使用一个元素两次,也就是必须为两个不同index对应数组元素的和与target相同。需要注意返回结果的index是从1开始计算的index。
该题可借助双指针实现,声明两个变量分别记录从左到右遍历的index和从右往前遍历的index;
- 声明两个变量,int l 代表从左到右遍历的数组index,int r 代表从右往前遍历的数组index;
- 当 l<r 时,判断arr[l]+arr[r]的值与target的大小。若arr[l]+arr[r] > target,由于数组元素单调递增的特性,只需将 index r 往左移,则能将两数之和减少,可能达到等于target的要求;若arr[l]+arr[r] < target,则需将 index l 往右移,即可将两数之和增大,可能达到等于target的要求;若 arr[l]+arr[r] == target,则此时 index l 和 index r 已找到,注意返回值中index为从1开始计算的;
- 重复步骤2。
算法实现(C++)
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> retVector;
retVector.clear();
int l = 0;//定义从左到右的index
int r = numbers.size();//定义从右往左的index
while (l < r)
{
int sum = numbers[l] + numbers[r];//计算两数之和
if (sum < target) ++l;//sum < target时,需要 index l 右移
else if (sum > target) --r;//sum > target时,需要 index r 左移
else {
retVector.push_back(l + 1);
retVector.push_back(r + 1);
return retVector;
}
}
retVector.push_back(-1);
retVector.push_back(-1);
return retVector;
}
}
复杂度分析
- 时间复杂度:O(n),每个元素最多被访问一次,遍历次数最多为数组大小;
- 空间复杂度:O(1),只借助了双指针(index l 和 index r 两个元素)来记录数组下标。