一.题目:
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:
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 thesame element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
意思:在一个有序的数组中,找到两个元素的和等于target的两个元素的索引。
注意:首先是一个有序的数组,其次题意给出一定有解条件,若无此条件应该考虑无解,输入数组为空,有多解(返回任意解)等情况
思路:1.暴力法,双重循环。e.g: 第一个元素和剩余其余元素的组合情况。第二个元素和第二个元素之后的组合(不建议) O(n^2)
2.暴力法有一个优化就是利用数组的有序性,当在第一层固定了一个元素,使用二分查找去搜索target-nums[i]; O(nlogn)
3.双索引技术。在数组的头和尾设置两个索引,首先判断当前的两个索引的和发否等于target若相等记录index,并挑出循环返回。 若小于则头加加,若大于尾减减。 O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
//assert(numbers.size()>=2);
int i =0,j=numbers.size()-1;
vector<int> tempindex;
while(i<j)
{
if((numbers[i]+numbers[j]) == target)
{
//int res[2]={i+1,j+1};
//return vector<int>(res,res+2)
tempindex.push_back(i+1); //注意看题返回的索引不是从0开始的
tempindex.push_back(j+1);
break; //这里处理不当,这个时候应该直接返回,不然不利于处理无解的情况 return tempindex;
}else if((numbers[i]+numbers[j]) < target)
{
i++;
}
else{
j--;
}
}
//若运行完while循环还未找到,可以作无解处理
return tempindex;
}
};