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: [1,2]

1. hash-table
2. two pointers

/*solution 1 ,use hash-table 8ms*/
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
if(numbers.empty())
return {};
unordered_map<int,int> hash;
vector<int> res(2,0);
for(int i=0;i<numbers.size();i++){
int tmp=target-numbers[i];
if(hash.find(tmp)!=hash.end()){
res[0]=hash[tmp]+1;
res[1]=i+1;
}
else
hash[numbers[i]]=i;
}
return res;
}
};



/*solution2 two pointers 8ms*/
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0, right = numbers.size() - 1;
vector<int> res;
while(left < right){
long long val = numbers[left] + numbers[right];
if(val == target){
res.push_back(left + 1);
res.push_back(right + 1);
return res;
}
else if(val < target)
left++;
else
right--;
}
return res;
}
};



学籍管理系统文档

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017