167. 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

分析

给定数组已经排好序,所以可从后往前遍历,找到比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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值