167. Two Sum II - Input array is sorted
Problem:
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.
思路:
Solution (C++):
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
if (n < 2) return vector<int>{};
int i = 0, j = n-1;
vector<int> res(2, 0);
while (i < j) {
if (numbers[i] + numbers[j] == target) { res[0] = i+1; res[1] = j+1; break; }
else if (numbers[i] + numbers[j] < target) ++i;
else if (numbers[i] + numbers[j] > target) --j;
}
return res;
}
性能:
Runtime: 4 ms Memory Usage: 7.3 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
![](https://www.cnblogs.com/images/cnblogs_com/dysjtu1995/1468066/t_qrcode_for_gh_547d3edeac81_258.jpg)
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。