167. Two Sum II - Input array is sorted

来源:互联网 发布:decision tree算法 编辑:程序博客网 时间:2024/06/06 02:26

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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解题思路:

设置两个变量index1, index2分别指向数组首尾两端,判断两变量指向的值之和与target的关系:
1. 和与target相等,保存index+1和index+2,返回。
2. 和小于target,index1++;
3. 和大于target,index2–。
如果不满足1,一直遍历到index1>=index2结束循环。

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {        vector<int> result;        int index1 = 0;        int index2 = numbers.size() - 1;        while (index1 < index2) {            int sum = numbers[index1] + numbers[index2];            if (sum == target) {                result.push_back(index1 + 1);                result.push_back(index2 + 1);                break;            }            else if (sum > target) {                index2--;            }            else {                index1++;            }        }        return result;    }};
0 0