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.
根据体育首先想到了一个二层循环,结合章节要求的two-pointer,所以定义两个指针用来遍历数组。最主要的问题在于循环条件的设置。具体内容见代码及相关注释,不再详述。
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>&numbers, int target) { 4 int *index1 = &numbers[0];//定义两个指针,指向同一个数组 5 int *index2 = &numbers[0]; 6 int counter1 = 0;//用来记录数组下标 7 while (2*index1[counter1]<=target) {//以index1为基准,未达到括号里的条件则无需继续循环 8 for (int i = counter1+1; i < numbers.size(); i++)//从index1往后进行遍历寻找 9 { 10 if (index1[counter1] + index2[i] == target) {//找到则返回条件值,并处理指针; 11 index1 = NULL; 12 index2 = NULL; 13 return{ counter1+1,i+1 }; 14 } 15 else if (index1[counter1] + index2[i] > target) break; //否则向后移动继续寻找 16 } 17 counter1++; 18 } 19 index1 = NULL; 20 index2 = NULL; 21 return{};//未找到,返回空。 22 } 23 };