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

相当于第1题又重做了一遍.注意map<int, int> hash;定义方式.
(O(n)) time, (O(1)) space.
自己代码:

vector<int> twoSum(vector<int>& A, int ta) {
    vector<int> result;
    map<int, int> hash;
    int i, temp, max, min;

    for (i = 0; i < A.size(); i++) {
        temp = ta - A[i];
        if (hash.find(temp) != hash.end()) { //找到了
            max = hash[temp] > i ? hash[temp] : i;
            min = hash[temp] > i ? i : hash[temp];
            result.push_back(min + 1); // bcz base = 1
            result.push_back(max + 1);
            return result;
            //下面代码,就是没找到的话,将对应<k, v>存入hash
        }
        hash[A[i]] = i;
    }
    return result;
}
原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7357017.html