167. Two Sum II - Input array is sorted 难度:medium

来源:互联网 发布:知达常青藤中学校费用 编辑:程序博客网 时间:2024/05/17 04:27

题目:

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


思路:

定义两个指针i,j分别指向数组的开头和结尾,当i,j所指元素的和大于所给元素时,j减一,当i,j所指元素的和小于所给元素时i加一,指导i,j所指元素的和等于所给元素。


程序:

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


0 0
原创粉丝点击