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

 

典型的双指针问题。

初始化左指针left指向数组起始,初始化右指针right指向数组结尾。

根据已排序这个特性,

(1)如果numbers[left]与numbers[right]的和tmp小于target,说明应该增加tmp,因此left右移指向一个较大的值。

(2)如果tmp大于target,说明应该减小tmp,因此right左移指向一个较小的值。

(3)tmp等于target,则找到,返回left+1和right+1。(注意以1为起始下标)

时间复杂度O(n): 扫一遍

空间复杂度O(1)

ps: 严格来说,两个int的加和可能溢出int,因此将tmp和target提升为long long int再进行比较更鲁棒。

 

vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> ret(2,-1);
        int left = 0;
        int right = numbers.size()-1;
        while(left < right)
        {
            int tmp = numbers[left]+numbers[right];
            if(tmp == target)
            {
                ret[0] = left+1;
                ret[1] = right+1;
                return ret;
            }
            else if(tmp < target)
            //make tmp larger
                left ++;
            else
            //make tmp smaller
                right --;
        }
         //上面条件不符合时返回
        return ret;
    }

以下是我的测试用例,全部测试通过:

int main()
{
    Solution s;
    int A[4] = {2, 7, 11, 15};
    vector<int> numbers1(A, A+4);
    vector<int> ret = s.twoSum(numbers1, 9);
    cout << ret[0] << ", " << ret[1] << endl;

    int B[2] = {1, 1};
    vector<int> numbers2(B, B+2);
    ret = s.twoSum(numbers2, 2);
    cout << ret[0] << ", " << ret[1] << endl;

    int C[3] = {1,2,3};
    vector<int> numbers3(C, C+3);
    ret = s.twoSum(numbers3, 5);
    cout << ret[0] << ", " << ret[1] << endl;

    return 0;
}


转自:http://www.cnblogs.com/ganganloveu/p/4198968.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值