leetcode---C++实现---167. Two Sum II - Input array is sorted(两数之和 II - 输入有序数组)

题目

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;

  1. 声明两个变量,int l 代表从左到右遍历的数组index,int r 代表从右往前遍历的数组index;
  2. 当 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开始计算的;
  3. 重复步骤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 两个元素)来记录数组下标。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值