leetcode——Two Sum II - Input array is sorted

本文探讨了在已排序的数组中寻找两个数使它们的和等于特定目标值的问题。提出了三种解决方案,包括简单的双重循环、结合二分查找的方法及高效的双指针技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题目:

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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解析:题目要求在已排好序的数组中找到两个和为指定值的项,并返回以1为起点的下标。

笔者尝试了三种算法:

第一种简单粗暴,直接两重循环暴力搜索,复杂度为O(n^2),不过很不幸,结果超出时间限制;

算法二是通过一重循环穷举第一项,同时对第二项进行二分查找(给定数组已排好序),复杂度为O(nlogn),虽然通过,但是效率还不是很高;

class Solution {
public:
	vector<int> twoSum(vector<int>& numbers, int target) {
		vector<int> ans;
		int i, j = -1;
		for(i=0; i<numbers.size(); i++)
		{
			int l = 0, h = numbers.size()-1;
			while(l <= h)
			{
				if(numbers[(l+h)/2] == (target-numbers[i]))
				{
					j = (l + h) / 2;
					if(j == i)	j ++;
					break;
				}
				else if(numbers[(l+h)/2] < (target-numbers[i]))
					l = (l + h) / 2 + 1;
				else	h = (l + h) / 2 - 1;
			}
			if(j != -1)	break;
		}
		ans.push_back(i+1);
		ans.push_back(j+1);
		return ans;
	}
};



算法三:短小精悍,且高效,复杂度为O(n)。设定两个变量i和j分别指向数组开头或者结尾,然后对向收缩,若numbers[i] + numbers[j]等于target,结束;若numbers[i]+numbers[j]<target,则i++;否则j++。详见代码:
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> ans;
        int i = 0, j = numbers.size()-1;
	while(i < j)
	{
		if(numbers[i] + numbers[j] == target)	break;
		else if(numbers[i] + numbers[j] < target)	i ++;
		else	j --;
	}
	ans.push_back(i+1);
	ans.push_back(j+1);
	return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值