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
Subscribe to see which companies asked this question.
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 class Solution { 6 public: 7 vector<int> twoSum(vector<int>& numbers, int target) { 8 vector<int> v; 9 int begin = 0; 10 int end = numbers.size() - 1; 11 12 while (begin<end) 13 { 14 if ((numbers[begin] + numbers[end]) == target) 15 { 16 v.push_back(begin + 1); 17 v.push_back(end + 1); 18 break; 19 } 20 else 21 if ((numbers[begin] + numbers[end])>target) 22 { 23 end--; 24 } 25 else 26 begin++; 27 } 28 return v; 29 } 30 }; 31 int main() 32 { 33 vector<int> v{ 2, 7, 11, 15 }; 34 int target = 9; 35 vector<int> v1; 36 Solution s; 37 v1 = s.twoSum(v, target); 38 for (auto a : v1) 39 cout << a << " "; 40 system("pause"); 41 return 0; 42 }