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

原文链接: https://www.cnblogs.com/dysjtu1995/p/12640044.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    167. Two Sum II - Input array is sorted

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/340140

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午12:26
下一篇 2023年3月2日 上午12:27

相关推荐