[leetcode] 167. Two Sum II - Input array is sorted 解题报告

来源:互联网 发布:win10家庭版装c语言 编辑:程序博客网 时间:2024/05/22 09:38

题目链接:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

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


思路: 简单的two points.

代码如下:

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {        int len=numbers.size(), left = 0, right = len-1;        while(left < right)        {            int val = numbers[left] + numbers[right];            if(val == target) return vector<int>{left+1, right+1};            else if(val > target) right--;            else left++;        }        return {};    }};



0 0
原创粉丝点击