167. Two Sum II - Input array is sorted

来源:互联网 发布:sql distinct多表 编辑:程序博客网 时间:2024/05/22 15:06

题目

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

分析

给定数组已经排好序,所以可从后往前遍历,找到比target小的则记录下index,对target做减法,在数组中找剩余的值,需要注意的是,当数组规模很大时,比target小的数可能不止一个,所以第一次相减的差可能并不在数组中,需要对查找结果进行判断,已决定循环是否继续,同时当数组为[-3,3,2,90],target为0时,会先找到-3作为index2,3作为index1,故要在末尾进行numbers[index1-1]与numbers[index2-1]的值大小的判断,来决定index1和index2在结果中的前后顺序。

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {        int index1,index2;        for(int i=numbers.size()-1;i>=0;--i)        {            if(numbers[i]<=target)            {                target-=numbers[i];                index2=i+1;                vector<int>::iterator it=find(numbers.begin(),numbers.end(),target);                if(it!=numbers.end())//判断target剩余值是否在数组中,在的话对index1赋值                {                    index1=(int)(it-numbers.begin())+1;                    break;                }                else//否则还原target,继续循环                    target+=numbers[i];            }                    }        vector<int> res;        if(numbers[index1-1]>numbers[index2-1])//对index1与index2的值大小判断,决定前后顺序            res={index2,index1};        else            res={index1,index2};        return res;    }};


0 0
原创粉丝点击