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

posted @ 2020-04-05 23:51  littledy  阅读(117)  评论(0编辑  收藏  举报