1.题目大意
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
给定一个已排序的整数数组numbers,找出其中两个相加能够等于target的数字。输出它们在数组里的序号。
2.思路
看了一下这道题的其它解题报告,有的写得太复杂了。普遍的第一个思路是两个for循环,这个思路是不大好的,时间复杂性是$O(n^2)$,数组稍微大一点的时候就会超时。第二个比较普遍思路是找target/2,以此为分界线,往前和往后判断,但这个方法其实也不是最好的。第三个思路就是接下来要说的,复杂性为$O(n)$的思路——从两端开始,分别记为i和j:
(1)如果numbers[i]+numbers[j]的结果大于target的话就把j缩小,因为如果再把i增加,那么numbers[i]+numbers[j]结果就更大了。
(2)如果numbers[i]+numbers[j]的结果小于target的话就把i增大,因为如果再把j减小,那么numbers[i]+numbers[j]结果就更小了。
3.代码
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int i=0,j=numbers.size()-1; while(i<j) { if(numbers[i]+numbers[j]==target) return {i+1,j+1}; else if(numbers[i]+numbers[j]>target) j--; else if(numbers[i]+numbers[j]<target) i++; } return {0,0}; } };