167.leetcode Two Sum II - Input array is sorted(medium)[两数求和固定值]

来源:互联网 发布:马云说的阿里健康 编辑:程序博客网 时间:2024/06/06 12:52

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.

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

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

与2sum的解决方法相似,从两端向中间遍历,当得到第一个和为target的break,如果比target大则末端指针减1,如果比target小则前端指针加1.


0 0
原创粉丝点击