[LeetCode]167. Two Sum II - Input array is sorted(输入两数和 II - 输出排序数组这两数位置)

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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题目大意:
给定一个升序的数组和一个正整数target,找出数组中哪两个数加起来得到target,输出这两个数的位置,注意输出的前一个数一定要比后一个数小。

代码如下:

#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> Array(2);
        int left = 0;
        int right = numbers.size() - 1;
        while(left < right){
            if(numbers[left]+numbers[right] == target){
                Array[0] = left+1;
                Array[1] = right+1;
                return Array;
            }
            else if(numbers[left]+numbers[right] > target)
                right--;
            else
                left++;
        }
        return Array;
    }
};
int main()
{
    Solution a;
    int A[4] = {2, 7, 11, 15};
    vector<int> numbers1(A, A+4);
    vector<int> Array = a.twoSum(numbers1, 9);
    cout << Array[0] << ", " << Array[1] << endl;

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

    int C[3] = {1,5,9};
    vector<int> numbers3(C, C+3);
    Array = a.twoSum(numbers3, 14);
    cout << Array[0] << ", " << Array[1] << endl;
    cout << "Hello world!" << endl;
    return 0;
}

注意:

  1. 看Discuss有人直接 return { l + 1 , r + 1}; 貌似节省了空间
  2. 见到有人这么说,两个int的加和可能溢出int,将tmp和target提升为long long int再进行更好。
  3. 最初想法是二分查找,感觉太复杂就没写,可以参考下面的链接http://m.blog.csdn.net/article/details?id=53133707(该博主二分法描述部分是错误的,但是代码对了)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值