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

Note:
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 and you may not use thesame element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


意思:在一个有序的数组中,找到两个元素的和等于target的两个元素的索引。

注意:首先是一个有序的数组,其次题意给出一定有解条件,若无此条件应该考虑无解,输入数组为空,有多解(返回任意解)等情况

思路:1.暴力法,双重循环。e.g: 第一个元素和剩余其余元素的组合情况。第二个元素和第二个元素之后的组合(不建议)  O(n^2)

             2.暴力法有一个优化就是利用数组的有序性,当在第一层固定了一个元素,使用二分查找去搜索target-nums[i];      O(nlogn)

            3.双索引技术。在数组的头和尾设置两个索引,首先判断当前的两个索引的和发否等于target若相等记录index,并挑出循环返回。 若小于则头加加,若大于尾减减。       O(n)

 

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        //assert(numbers.size()>=2);
        int i =0,j=numbers.size()-1;
        vector<int> tempindex;
        while(i<j)
        {
            if((numbers[i]+numbers[j]) == target)
            {
                //int res[2]={i+1,j+1};
                //return vector<int>(res,res+2)
                tempindex.push_back(i+1);  //注意看题返回的索引不是从0开始的
                tempindex.push_back(j+1);
                break;                   //这里处理不当,这个时候应该直接返回,不然不利于处理无解的情况 return  tempindex;
            }else if((numbers[i]+numbers[j]) < target)
            {
                i++;
            }
            else{
                j--;
            }
        }
        //若运行完while循环还未找到,可以作无解处理
        return tempindex;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值