167. Two Sum II - Input array is sorted
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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题目大意:
给定一个升序的数组和一个正整数target,找出数组中哪两个数加起来得到target,输出这两个数的位置,注意输出的前一个数一定要比后一个数小。
代码如下:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> Array(2);
int left = 0;
int right = numbers.size() - 1;
while(left < right){
if(numbers[left]+numbers[right] == target){
Array[0] = left+1;
Array[1] = right+1;
return Array;
}
else if(numbers[left]+numbers[right] > target)
right--;
else
left++;
}
return Array;
}
};
int main()
{
Solution a;
int A[4] = {2, 7, 11, 15};
vector<int> numbers1(A, A+4);
vector<int> Array = a.twoSum(numbers1, 9);
cout << Array[0] << ", " << Array[1] << endl;
int B[2] = {5, 5};
vector<int> numbers2(B, B+2);
Array = a.twoSum(numbers2, 10);
cout << Array[0] << ", " << Array[1] << endl;
int C[3] = {1,5,9};
vector<int> numbers3(C, C+3);
Array = a.twoSum(numbers3, 14);
cout << Array[0] << ", " << Array[1] << endl;
cout << "Hello world!" << endl;
return 0;
}
注意:
- 看Discuss有人直接 return { l + 1 , r + 1}; 貌似节省了空间
- 见到有人这么说,两个int的加和可能溢出int,将tmp和target提升为long long int再进行更好。
- 最初想法是二分查找,感觉太复杂就没写,可以参考下面的链接http://m.blog.csdn.net/article/details?id=53133707(该博主二分法描述部分是错误的,但是代码对了)